本文整理匯總了Python中django.utils.six.text_type方法的典型用法代碼示例。如果您正苦於以下問題:Python six.text_type方法的具體用法?Python six.text_type怎麽用?Python six.text_type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.six
的用法示例。
在下文中一共展示了six.text_type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: javascript_quote
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def javascript_quote(s, quote_double_quotes=False):
msg = (
"django.utils.text.javascript_quote() is deprecated. "
"Use django.utils.html.escapejs() instead."
)
warnings.warn(msg, RemovedInDjango19Warning, stacklevel=2)
def fix(match):
return "\\u%04x" % ord(match.group(1))
if type(s) == bytes:
s = s.decode('utf-8')
elif type(s) != six.text_type:
raise TypeError(s)
s = s.replace('\\', '\\\\')
s = s.replace('\r', '\\r')
s = s.replace('\n', '\\n')
s = s.replace('\t', '\\t')
s = s.replace("'", "\\'")
s = s.replace('</', '<\\/')
if quote_double_quotes:
s = s.replace('"', '"')
return ustring_re.sub(fix, s)
示例2: localize
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def localize(value, use_l10n=None):
"""
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if isinstance(value, bool):
return mark_safe(six.text_type(value))
elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
elif isinstance(value, datetime.date):
return date_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.time):
return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
else:
return value
示例3: make_bytes
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def make_bytes(self, value):
"""Turn a value into a bytestring encoded in the output charset."""
# Per PEP 3333, this response body must be bytes. To avoid returning
# an instance of a subclass, this function returns `bytes(value)`.
# This doesn't make a copy when `value` already contains bytes.
# Handle string types -- we can't rely on force_bytes here because:
# - under Python 3 it attempts str conversion first
# - when self._charset != 'utf-8' it re-encodes the content
if isinstance(value, bytes):
return bytes(value)
if isinstance(value, six.text_type):
return bytes(value.encode(self.charset))
# Handle non-string types (#16494)
return force_bytes(value, self.charset)
# These methods partially implement the file-like object interface.
# See http://docs.python.org/lib/bltin-file-objects.html
# The WSGI server must call this method upon completion of the request.
# See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
示例4: effective_default
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def effective_default(self, field):
"""
Returns a field's effective database default value
"""
if field.has_default():
default = field.get_default()
elif not field.null and field.blank and field.empty_strings_allowed:
if field.get_internal_type() == "BinaryField":
default = six.binary_type()
else:
default = six.text_type()
else:
default = None
# If it's a callable, call it
if six.callable(default):
default = default()
# Run it through the field's get_db_prep_save method so we can send it
# to the database.
default = field.get_db_prep_save(default, self.connection)
return default
示例5: last_executed_query
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
# Convert params to contain Unicode values.
to_unicode = lambda s: force_text(s, strings_only=True, errors='replace')
if isinstance(params, (list, tuple)):
u_params = tuple(to_unicode(val) for val in params)
elif params is None:
u_params = ()
else:
u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()}
return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params)
示例6: date_error_message
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages['unique_for_date'],
code='unique_for_date',
params={
'model': self,
'model_name': six.text_type(capfirst(opts.verbose_name)),
'lookup_type': lookup_type,
'field': field_name,
'field_label': six.text_type(capfirst(field.verbose_name)),
'date_field': unique_for,
'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
}
)
示例7: csrf
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val()}
示例8: assertHTMLEqual
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def assertHTMLEqual(self, html1, html2, msg=None):
"""
Asserts that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The passed-in arguments must be valid HTML.
"""
dom1 = assert_and_parse_html(self, html1, msg,
'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg,
'Second argument is not valid HTML:')
if dom1 != dom2:
standardMsg = '%s != %s' % (
safe_repr(dom1, True), safe_repr(dom2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
six.text_type(dom1).splitlines(),
six.text_type(dom2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
示例9: contents
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def contents(self):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
try:
f, attr, value = lookup_field(field, obj, model_admin)
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = EMPTY_CHANGELIST_VALUE
else:
if f is None:
boolean = getattr(attr, "boolean", False)
if boolean:
result_repr = _boolean_icon(value)
else:
result_repr = smart_text(value)
if getattr(attr, "allow_tags", False):
result_repr = mark_safe(result_repr)
else:
result_repr = linebreaksbr(result_repr)
else:
if isinstance(f.rel, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f)
return conditional_escape(result_repr)
示例10: _make_token_with_timestamp
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def _make_token_with_timestamp(self, user, timestamp):
# timestamp is number of days since 2001-1-1. Converted to
# base 36, this gives us a 3 digit string until about 2121
ts_b36 = int_to_base36(timestamp)
# By hashing on the internal state of the user and using state
# that is sure to change (the password salt will change as soon as
# the password is set, at least for current Django auth, and
# last_login will also change), we produce a hash that will be
# invalid as soon as it is used.
# We limit the hash to 20 chars to keep URL short
key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
# Ensure results are consistent across DB backends
login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)
value = (six.text_type(user.pk) + user.password +
six.text_type(login_timestamp) + six.text_type(timestamp))
hash = salted_hmac(key_salt, value).hexdigest()[::2]
return "%s-%s" % (ts_b36, hash)
示例11: regex
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def regex(self):
"""
Returns a compiled regular expression, depending upon the activated
language-code.
"""
language_code = get_language()
if language_code not in self._regex_dict:
if isinstance(self._regex, six.string_types):
regex = self._regex
else:
regex = force_text(self._regex)
try:
compiled_regex = re.compile(regex, re.UNICODE)
except re.error as e:
raise ImproperlyConfigured(
'"%s" is not a valid regular expression: %s' %
(regex, six.text_type(e)))
self._regex_dict[language_code] = compiled_regex
return self._regex_dict[language_code]
示例12: webhook_pull
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def webhook_pull(request, remote='origin'):
if request.method == 'POST':
try:
log = Git().pull(remote)
s = StringIO()
call_command('sync_waliki', stdout=s)
s.seek(0)
r = {'pull': log, 'sync': s.read()}
status_code = 200
except Exception as e:
r = {'error': text_type(e)}
status_code = 500
return HttpResponse(json.dumps(r), status=status_code,
content_type="application/json")
return HttpResponse("POST to %s" % reverse("waliki_webhook_pull", args=(remote,)))
示例13: test_model_instance
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def test_model_instance(self):
# With no matching instances, the default should be used
page = Page(title="Title", type="newpage")
path = page.get_absolute_url()
self.assertEqual(get_metadata(path).title.value, "example.com")
# Check that a new metadata instance is created
old_count = Coverage._meta.get_model('modelinstance').objects.all().count()
page.save()
new_count = Coverage._meta.get_model('modelinstance').objects.all().count()
self.assertEqual(new_count, old_count + 1)
# Check that the correct data is loaded
assert 'New Page title' not in six.text_type(get_metadata(path).title)
Coverage._meta.get_model('modelinstance').objects.filter(_content_type=self.page_content_type,
_object_id=page.id).update(title="New Page title")
self.assertEqual(get_metadata(path).title.value, 'New Page title')
示例14: get_authorization_header
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def get_authorization_header(self, request):
"""
Return request's 'Authorization:' header, as a bytestring.
Hide some test client ickyness where the header can be unicode.
"""
auth = request.META.get("HTTP_AUTHORIZATION", b"").replace("Bearer ", "")
if isinstance(auth, text_type):
# Work around django test client oddness
auth = auth.encode(HTTP_HEADER_ENCODING)
return auth
示例15: clean
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import text_type [as 別名]
def clean(self):
# self.validate_unique()
cleaned_data = super(CheckUniqueTogether, self).clean()
unique_fields = self.get_unique_together()
if isinstance(unique_fields, (list, tuple)):
unique_filter = {}
instance = self.instance
model_name = instance._meta.verbose_name
for unique_field in unique_fields:
field = instance._meta.get_field(unique_field)
if field.editable and unique_field in self.fields:
unique_filter[unique_field] = cleaned_data.get(
unique_field)
else:
unique_filter[unique_field] = getattr(
instance, unique_field)
for k, v in unique_filter.items():
if not v:
return
existing_instances = type(instance).objects.filter(
**unique_filter).exclude(pk=instance.pk)
if existing_instances:
field_labels = [
instance._meta.get_field(f).verbose_name
for f in unique_fields
]
field_labels = text_type(get_text_list(field_labels, _('and')))
msg = _("%(model_name)s with this %(field_labels)s already exists.") % {
'model_name': model_name, 'field_labels': field_labels, }
for unique_field in unique_fields:
if unique_field in self.fields:
self.add_error(unique_field, msg)