当前位置: 首页>>代码示例>>Python>>正文


Python encoding.smart_str方法代码示例

本文整理汇总了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 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:26,代码来源:authentication.py

示例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) 
开发者ID:metakgp,项目名称:naarad-source,代码行数:20,代码来源:frontend.py

示例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.") 
开发者ID:restran,项目名称:fomalhaut-panel,代码行数:22,代码来源:models.py

示例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)) 
开发者ID:and3rson,项目名称:django-searchable-select,代码行数:22,代码来源:views.py

示例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 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:24,代码来源:leonardo_tags.py

示例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 
开发者ID:labd,项目名称:wagtailstreamforms,代码行数:20,代码来源:submission_list.py

示例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 
开发者ID:Hipo,项目名称:drf-extra-fields,代码行数:20,代码来源:geo_fields.py

示例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 
开发者ID:django-userena-ce,项目名称:django-userena-ce,代码行数:20,代码来源:managers.py

示例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") 
开发者ID:django-userena-ce,项目名称:django-userena-ce,代码行数:26,代码来源:check_permissions.py

示例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 
开发者ID:iguana-project,项目名称:iguana,代码行数:22,代码来源:filter.py

示例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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:15,代码来源:fields.py

示例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 
开发者ID:archesproject,项目名称:arches,代码行数:31,代码来源:betterJSONSerializer.py

示例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) 
开发者ID:stormsha,项目名称:StormOnline,代码行数:10,代码来源:relate.py

示例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) 
开发者ID:qwiglydee,项目名称:drf-mongo-filters,代码行数:4,代码来源:fields.py

示例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 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:7,代码来源:xform_instance_parser.py


注:本文中的django.utils.encoding.smart_str方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。