本文整理汇总了Python中django.utils.encoding.smart_str方法的典型用法代码示例。如果您正苦于以下问题:Python encoding.smart_str方法的具体用法?Python encoding.smart_str怎么用?Python encoding.smart_str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.encoding
的用法示例。
在下文中一共展示了encoding.smart_str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_jwt_value
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def _get_jwt_value(self, request):
auth = get_authorization_header(request).split()
auth_header_prefix = getattr(settings, 'JWT_AUTH_HEADER_PREFIX', 'JWT')
if not auth:
if getattr(settings, 'JWT_AUTH_COOKIE', None):
return request.COOKIES.get(settings.JWT_AUTH_COOKIE)
return None
if smart_str(auth[0]) != auth_header_prefix:
return None
if len(auth) == 1:
msg = 'Invalid Authorization header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = ('Invalid Authorization header. Credentials string '
'should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
jwt_value = auth[1]
if type(jwt_value) is bytes:
jwt_value = jwt_value.decode('utf-8')
return jwt_value
示例2: get_html
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def get_html(data):
template_raw = open('feed.tmpl', 'r').read()
for post in data:
if 'message' in post:
if (type(post['message']) is str):
post['message'] = fixnewlines(post['message'])
if 'flag' not in post :
post['message'] = enable_links(post['message'])
post['flag'] = 1
post['message'] = post['message'].replace("\"","'")
post['short_message'] = truncate(post['message'],150)
post['read_more'] = truncate_length(post['message'],150)
json.dump(data, open('docs/feed.json', 'w'))
template = Template(template_raw)
html = template.render(data=data)
# smart_str helps in unicode rendering
return smart_str(html)
示例3: get_hexdigest
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return hashlib.md5(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return hashlib.sha1(salt + raw_password).hexdigest()
elif algorithm == 'sha256':
return hashlib.sha256(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
示例4: filter_models
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def filter_models(request):
model_name = request.GET.get('model')
search_field = request.GET.get('search_field')
value = request.GET.get('q')
limit = int(request.GET.get('limit', 10))
try:
model = get_model(model_name)
except LookupError as e: # pragma: no cover
return JsonResponse(dict(status=400, error=e.message))
except (ValueError, AttributeError) as e: # pragma: no cover
return JsonResponse(dict(status=400, error='Malformed model parameter.'))
values = model.objects.filter(**{'{}__icontains'.format(search_field): value})[:limit]
values = [
dict(pk=v.pk, name=smart_str(v))
for v
in values
]
return JsonResponse(dict(result=values))
示例5: render
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def render(self, context):
args = [arg.resolve(context) for arg in self.args]
kwargs = dict([
(smart_str(k, 'ascii'), v.resolve(context))
for k, v in self.kwargs.items()])
view_name = self.view_name.resolve(context)
urlconf = self.urlconf.resolve(context)
try:
url = do_app_reverse(
view_name, urlconf, args=args, kwargs=kwargs,
current_app=context.current_app)
except NoReverseMatch:
if self.asvar is None:
raise
url = ''
if self.asvar:
context[self.asvar] = url
return ''
else:
return url
示例6: csv
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def csv(self):
queryset = self.get_queryset()
data_fields = self.object.get_data_fields()
data_headings = [smart_str(label) for name, label in data_fields]
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = "attachment;filename=export.csv"
writer = csv.writer(response)
writer.writerow(data_headings)
for s in queryset:
data_row = []
form_data = s.get_data()
for name, label in data_fields:
data_row.append(smart_str(form_data.get(name)))
writer.writerow(data_row)
return response
示例7: to_representation
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def to_representation(self, value):
"""
Transform POINT object to json.
"""
if value is None:
return value
if isinstance(value, GEOSGeometry):
value = {
"latitude": value.y,
"longitude": value.x
}
if self.str_points:
value['longitude'] = smart_str(value.pop('longitude'))
value['latitude'] = smart_str(value.pop('latitude'))
return value
示例8: create_userena_profile
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def create_userena_profile(self, user):
"""
Creates an :class:`UserenaSignup` instance for this user.
:param user:
Django :class:`User` instance.
:return: The newly created :class:`UserenaSignup` instance.
"""
if isinstance(user.username, str):
user.username = smart_str(user.username)
try:
profile = self.get(user=user)
except self.model.DoesNotExist:
profile = self.create(user=user, activation_key=generate_nonce())
return profile
示例9: handle
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def handle(self, **options):
permissions, users, warnings = UserenaSignup.objects.check_permissions()
output = options.pop("output")
test = options.pop("test")
if test:
self.stdout.write(40 * ".")
self.stdout.write(
"\nChecking permission management command. Ignore output..\n\n"
)
if output:
for p in permissions:
self.stdout.write("Added permission: %s\n" % p)
for u in users:
self.stdout.write(
"Changed permissions for user: %s\n"
% smart_str(u, encoding="utf-8", strings_only=False)
)
for w in warnings:
self.stdout.write("WARNING: %s\n" % w)
if test:
self.stdout.write("\nFinished testing permissions command.. continuing..\n")
示例10: render
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def render(self, context):
mods = [(smart_str(k, 'ascii'), op, v.resolve(context))
for k, op, v in self.mods]
if self.qdict:
qdict = self.qdict.resolve(context)
else:
qdict = None
# Internally work only with QueryDict
qdict = self._get_initial_query_dict(qdict)
# assert isinstance(qdict, QueryDict)
for k, op, v in mods:
qdict.setlist(k, self._process_list(qdict.getlist(k), op, v))
qstring = qdict.urlencode()
if qstring:
qstring = '?' + qstring
if self.asvar:
context[self.asvar] = qstring
return ''
else:
return qstring
示例11: to_python
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def to_python(self, value):
"""
Validates that the input is a fraction number. Returns a Fraction
instance. Returns None for empty values.
"""
if value in forms.fields.validators.EMPTY_VALUES:
return None
value = smart_str(value).strip()
try:
value = Fraction(value).limit_denominator(50)
except ValueError:
raise forms.fields.ValidationError(self.error_messages['invalid'])
return value
示例12: deserialize
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def deserialize(self, stream_or_string, **options):
self.options = options.copy()
self.stream = options.pop("stream", StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_keys = options.pop("use_natural_keys", False)
if isinstance(stream_or_string, str):
stream = StringIO(smart_str(stream_or_string))
elif isinstance(stream_or_string, bytes):
try:
stream = stream_or_string.decode("utf-8")
stream = StringIO(smart_str(stream))
except Exception as e:
print(e)
stream = stream_or_string
else:
stream = stream_or_string
try:
ret = self.handle_object(json.load(stream))
except TypeError as e:
print("=== +++ Error in JSONSerializer +++ ===")
print(e)
ret = None
return ret
示例13: init_request
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def init_request(self, *args, **kwargs):
self.relate_obj = None
for k, v in self.request.GET.items():
if smart_str(k).startswith(RELATE_PREFIX):
self.relate_obj = RelateObject(
self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v)
break
return bool(self.relate_obj)
示例14: to_representation
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def to_representation(self, value):
return smart_str(value)
示例15: clean_and_parse_xml
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_str [as 别名]
def clean_and_parse_xml(xml_string):
clean_xml_str = xml_string.strip()
clean_xml_str = re.sub(ur">\s+<", u"><", smart_unicode(clean_xml_str))
xml_obj = minidom.parseString(smart_str(clean_xml_str))
return xml_obj