當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。