Python django.utils.six.text_type() Examples

The following are 30 code examples of django.utils.six.text_type(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.six , or try the search function .
Example #1
Source File: context_processors.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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()} 
Example #2
Source File: schema.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #3
Source File: operations.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #4
Source File: response.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #5
Source File: views.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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,))) 
Example #6
Source File: formats.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #7
Source File: urlresolvers.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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] 
Example #8
Source File: text.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example #10
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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)),
            }
        ) 
Example #11
Source File: helpers.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #12
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #13
Source File: tokens.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #14
Source File: html.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self):
        return six.text_type(self) 
Example #15
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_keywords(self):
        """ Tests keywords are cleaned correctly. """
        exp = "Some, keywords&quot;, with,  other, chars&#39;"
        self.assertEqual(self.metadata.keywords.value, exp)
        exp = '<meta name="keywords" content="%s" />' % exp
        self.assertEqual(six.text_type(self.metadata.keywords), exp) 
Example #16
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_tags5(self):
        """ Tests the title is cleaned correctly. """
        self.path_metadata.title = "The Title <!-- with a comment -->"
        self.path_metadata.save()
        metadata = get_metadata(self.path_metadata._path)
        exp = 'The Title <!-- with a comment -->'
        self.assertEqual(metadata.title.value, exp)
        exp = '<title>%s</title>' % exp
        self.assertEqual(six.text_type(metadata.title), exp) 
Example #17
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_tags3(self):
        """ Tests the title is cleaned correctly. """
        self.path_metadata.title = "The < strong >Title</ strong >"
        self.path_metadata.save()
        metadata = get_metadata(self.path_metadata._path)
        exp = 'The < strong >Title</ strong >'
        self.assertEqual(metadata.title.value, exp)
        exp = '<title>%s</title>' % exp
        self.assertEqual(six.text_type(metadata.title), exp) 
Example #18
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_tags4(self):
        """ Tests the title is cleaned correctly. """
        self.path_metadata.title = "The <strong class=\"with&quot;inside\">Title</strong>"
        self.path_metadata.save()
        metadata = get_metadata(self.path_metadata._path)
        exp = 'The <strong class="with&quot;inside">Title</strong>'
        self.assertEqual(metadata.title.value, exp)
        exp = '<title>%s</title>' % exp
        self.assertEqual(six.text_type(metadata.title), exp) 
Example #19
Source File: tests.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_inline_tags2(self):
        """ Tests the title is cleaned correctly. """
        self.path_metadata.title = "The <strong id=\"mytitle\">Title</strong>"
        self.path_metadata.save()
        metadata = get_metadata(self.path_metadata._path)
        exp = 'The <strong id=\"mytitle\">Title</strong>'
        self.assertEqual(metadata.title.value, exp)
        exp = '<title>%s</title>' % exp
        self.assertEqual(six.text_type(metadata.title), exp) 
Example #20
Source File: token_gen_invites.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _make_hash_value(self, invite):
        return (
            six.text_type(invite.pk) + six.text_type(datetime.datetime.now()) +
            six.text_type(invite.group.name)
        ) 
Example #21
Source File: html.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        output = '<%s' % self.name
        for key, value in self.attributes:
            if value:
                output += ' %s="%s"' % (key, value)
            else:
                output += ' %s' % key
        if self.children:
            output += '>\n'
            output += ''.join(six.text_type(c) for c in self.children)
            output += '\n</%s>' % self.name
        else:
            output += ' />'
        return output 
Example #22
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def equals_lf(line):
    """
    Return True if line (a text or byte string) equals '\n'.
    """
    return line == ('\n' if isinstance(line, six.text_type) else b'\n') 
Example #23
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def endswith_lf(line):
    """
    Return True if line (a text or byte string) ends with '\n'.
    """
    return line.endswith('\n' if isinstance(line, six.text_type) else b'\n') 
Example #24
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def endswith_cr(line):
    """
    Return True if line (a text or byte string) ends with '\r'.
    """
    return line.endswith('\r' if isinstance(line, six.text_type) else b'\r') 
Example #25
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def load_middleware(self):
        """
        Populate middleware lists from settings.MIDDLEWARE_CLASSES.

        Must be called after the environment is fixed (see __call__ in subclasses).
        """
        self._view_middleware = []
        self._template_response_middleware = []
        self._response_middleware = []
        self._exception_middleware = []

        request_middleware = []
        for middleware_path in settings.MIDDLEWARE_CLASSES:
            mw_class = import_string(middleware_path)
            try:
                mw_instance = mw_class()
            except MiddlewareNotUsed as exc:
                if settings.DEBUG:
                    if six.text_type(exc):
                        logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
                    else:
                        logger.debug('MiddlewareNotUsed: %r', middleware_path)
                continue

            if hasattr(mw_instance, 'process_request'):
                request_middleware.append(mw_instance.process_request)
            if hasattr(mw_instance, 'process_view'):
                self._view_middleware.append(mw_instance.process_view)
            if hasattr(mw_instance, 'process_template_response'):
                self._template_response_middleware.insert(0, mw_instance.process_template_response)
            if hasattr(mw_instance, 'process_response'):
                self._response_middleware.insert(0, mw_instance.process_response)
            if hasattr(mw_instance, 'process_exception'):
                self._exception_middleware.insert(0, mw_instance.process_exception)

        # We only assign to this when initialization is complete as it is used
        # as a flag for initialization being complete.
        self._request_middleware = request_middleware 
Example #26
Source File: html.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        return ''.join(six.text_type(c) for c in self.children) 
Example #27
Source File: helpers.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, form, field, readonly_fields=None, model_admin=None):
        self.form = form  # A django.forms.Form instance
        if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
            self.fields = [field]
        else:
            self.fields = field
        self.has_visible_field = not all(field in self.form.fields and
                                         self.form.fields[field].widget.is_hidden
                                         for field in self.fields)
        self.model_admin = model_admin
        if readonly_fields is None:
            readonly_fields = ()
        self.readonly_fields = readonly_fields 
Example #28
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        """
        Returns the string representation.  If GDAL is installed,
        it will be 'pretty' OGC WKT.
        """
        try:
            return six.text_type(self.srs)
        except Exception:
            return six.text_type(self.wkt) 
Example #29
Source File: array.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def prepare_value(self, value):
        if isinstance(value, list):
            return self.delimiter.join(six.text_type(self.base_field.prepare_value(v)) for v in value)
        return value 
Example #30
Source File: models.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        return "%s | %s | %s" % (
            six.text_type(self.content_type.app_label),
            six.text_type(self.content_type),
            six.text_type(self.name))