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


Python six.text_type方法代码示例

本文整理汇总了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('"', '&quot;')
    return ustring_re.sub(fix, s) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:25,代码来源:text.py

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

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

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

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

示例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)),
            }
        ) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:base.py

示例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()} 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:context_processors.py

示例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)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:testcases.py

示例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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:27,代码来源:helpers.py

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

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

示例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,))) 
开发者ID:mgaitan,项目名称:waliki,代码行数:18,代码来源:views.py

示例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') 
开发者ID:whyflyru,项目名称:django-seo,代码行数:19,代码来源:tests.py

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

示例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) 
开发者ID:Wenvki,项目名称:django-idcops,代码行数:34,代码来源:forms.py


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