python类force_text()的实例源码

text.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def get_text_list(list_, last_word=ugettext_lazy('or')):
    """
    >>> get_text_list(['a', 'b', 'c', 'd'])
    'a, b, c or d'
    >>> get_text_list(['a', 'b', 'c'], 'and')
    'a, b and c'
    >>> get_text_list(['a', 'b'], 'and')
    'a and b'
    >>> get_text_list(['a'])
    'a'
    >>> get_text_list([])
    ''
    """
    if len(list_) == 0:
        return ''
    if len(list_) == 1:
        return force_text(list_[0])
    return '%s %s %s' % (
        # Translators: This string is used as a separator between list elements
        _(', ').join(force_text(i) for i in list_[:-1]),
        force_text(last_word), force_text(list_[-1]))
http.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def is_safe_url(url, host=None):
    """
    Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
    a different host and uses a safe scheme).

    Always returns ``False`` on an empty url.
    """
    if url is not None:
        url = url.strip()
    if not url:
        return False
    if six.PY2:
        try:
            url = force_text(url)
        except UnicodeDecodeError:
            return False
    # Chrome treats \ completely as / in paths but it could be part of some
    # basic auth credentials so we need to check both URLs.
    return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def permission_denied(request, exception, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )
edit.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_success_url(self):
        """
        Returns the supplied URL.
        """
        if self.success_url:
            # force_text can be removed with deprecation warning
            self.success_url = force_text(self.success_url)
            if PERCENT_PLACEHOLDER_REGEX.search(self.success_url):
                warnings.warn(
                    "%()s placeholder style in success_url is deprecated. "
                    "Please replace them by the {} Python format syntax.",
                    RemovedInDjango110Warning, stacklevel=2
                )
                url = self.success_url % self.object.__dict__
            else:
                url = self.success_url.format(**self.object.__dict__)
        else:
            try:
                url = self.object.get_absolute_url()
            except AttributeError:
                raise ImproperlyConfigured(
                    "No URL to redirect to.  Either provide a url or define"
                    " a get_absolute_url method on the Model.")
        return url
edit.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_success_url(self):
        if self.success_url:
            # force_text can be removed with deprecation warning
            self.success_url = force_text(self.success_url)
            if PERCENT_PLACEHOLDER_REGEX.search(self.success_url):
                warnings.warn(
                    "%()s placeholder style in success_url is deprecated. "
                    "Please replace them by the {} Python format syntax.",
                    RemovedInDjango110Warning, stacklevel=2
                )
                return self.success_url % self.object.__dict__
            else:
                return self.success_url.format(**self.object.__dict__)
        else:
            raise ImproperlyConfigured(
                "No URL to redirect to. Provide a success_url.")
dates.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_date_list(self, queryset, date_type=None, ordering='ASC'):
        """
        Get a date list by calling `queryset.dates/datetimes()`, checking
        along the way for empty lists that aren't allowed.
        """
        date_field = self.get_date_field()
        allow_empty = self.get_allow_empty()
        if date_type is None:
            date_type = self.get_date_list_period()

        if self.uses_datetime_field:
            date_list = queryset.datetimes(date_field, date_type, ordering)
        else:
            date_list = queryset.dates(date_field, date_type, ordering)
        if date_list is not None and not date_list and not allow_empty:
            name = force_text(queryset.model._meta.verbose_name_plural)
            raise Http404(_("No %(verbose_name_plural)s available") %
                          {'verbose_name_plural': name})

        return date_list
fields.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def to_python(self, value):
        """
        Validates that int() can be called on the input. Returns the result
        of int(). Returns None for empty values.
        """
        value = super(IntegerField, self).to_python(value)
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        # Strip trailing decimal and zeros.
        try:
            value = int(self.re_decimal.sub('', force_text(value)))
        except (ValueError, TypeError):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
utils.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def popen_wrapper(args, os_err_exc_type=CommandError, stdout_encoding='utf-8'):
    """
    Friendly wrapper around Popen.

    Returns stdout output, stderr output and OS status code.
    """
    try:
        p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
    except OSError as e:
        strerror = force_text(e.strerror, DEFAULT_LOCALE_ENCODING, strings_only=True)
        six.reraise(os_err_exc_type, os_err_exc_type('Error executing %s: %s' %
                    (args[0], strerror)), sys.exc_info()[2])
    output, errors = p.communicate()
    return (
        force_text(output, stdout_encoding, strings_only=True, errors='strict'),
        force_text(errors, DEFAULT_LOCALE_ENCODING, strings_only=True, errors='replace'),
        p.returncode
    )
message.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_text(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ADDRESS_HEADERS:
            val = ', '.join(sanitize_address(addr, encoding) for addr in getaddresses((val,)))
        else:
            val = Header(val, encoding).encode()
    else:
        if name.lower() == 'subject':
            val = Header(val).encode()
    return str(name), val
message.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def message(self):
        encoding = self.encoding or settings.DEFAULT_CHARSET
        msg = SafeMIMEText(self.body, self.content_subtype, encoding)
        msg = self._create_message(msg)
        msg['Subject'] = self.subject
        msg['From'] = self.extra_headers.get('From', self.from_email)
        msg['To'] = self.extra_headers.get('To', ', '.join(map(force_text, self.to)))
        if self.cc:
            msg['Cc'] = ', '.join(map(force_text, self.cc))
        if self.reply_to:
            msg['Reply-To'] = self.extra_headers.get('Reply-To', ', '.join(map(force_text, self.reply_to)))

        # Email header names are case-insensitive (RFC 2045), so we have to
        # accommodate that when doing comparisons.
        header_names = [key.lower() for key in self.extra_headers]
        if 'date' not in header_names:
            msg['Date'] = formatdate()
        if 'message-id' not in header_names:
            # Use cached DNS_NAME for performance
            msg['Message-ID'] = make_msgid(domain=DNS_NAME)
        for name, value in self.extra_headers.items():
            if name.lower() in ('from', 'to'):  # From and To are already handled
                continue
            msg[name] = value
        return msg
password_validation.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def validate(self, password, user=None):
        if not user:
            return

        for attribute_name in self.user_attributes:
            value = getattr(user, attribute_name, None)
            if not value or not isinstance(value, string_types):
                continue
            value_parts = re.split('\W+', value) + [value]
            for value_part in value_parts:
                if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
                    verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
                    raise ValidationError(
                        _("The password is too similar to the %(verbose_name)s."),
                        code='password_too_similar',
                        params={'verbose_name': verbose_name},
                    )
models.py 文件源码 项目:RobotFrameworkReporter 作者: ivanitskiy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def path_and_rename(instance, filename):
    ext = filename.split('.')[-1]
    if instance.pk:
        filename = '{}.{}'.format(instance.pk, ext)
    else:
        filename = '{}.{}'.format(uuid4().hex, ext)
    dirname = force_text(datetime.datetime.now().strftime(force_str('uploads/%Y/%m/%d/')))
    return os.path.join(dirname, filename)
views.py 文件源码 项目:my-first-blog 作者: AnkurBegining 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_confirmed = True
        user.save()
        login(request, user)
        return redirect('post_detail')
    else:
        return render(request, 'blog/post_list.html')
plugin.py 文件源码 项目:sentry-plugins 作者: getsentry 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def create_issue(self, request, group, form_data, **kwargs):
        json_data = {
            'story_type': 'bug',
            'name': force_text(form_data['title'], encoding='utf-8', errors='replace'),
            'description': force_text(form_data['description'], encoding='utf-8', errors='replace'),
            'labels': ['sentry'],
        }

        try:
            _url = self.build_api_url(group, 'stories')
            req = self.make_api_request(group.project, _url, json_data=json_data)
            body = safe_urlread(req)
        except requests.RequestException as e:
            msg = six.text_type(e)
            raise PluginError('Error communicating with Pivotal: %s' % (msg, ))

        try:
            json_resp = json.loads(body)
        except ValueError as e:
            msg = six.text_type(e)
            raise PluginError('Error communicating with Pivotal: %s' % (msg, ))

        if req.status_code > 399:
            raise PluginError(json_resp['error'])

        return json_resp['id']
operations.py 文件源码 项目:Plamber 作者: OlegKlimenko 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def last_executed_query(self, cursor, sql, params):
        return force_text(cursor.statement, errors='replace')
operations.py 文件源码 项目:Plamber 作者: OlegKlimenko 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def convert_textfield_value(self, value, expression, connection, context):
        # New in Django 1.8
        if value is not None:
            value = force_text(value)
        return value
test_views.py 文件源码 项目:django-filer-celery 作者: nephila 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_upload_no_form(self):
        self.assertEqual(Image.objects.count(), 0)
        folder = Folder.objects.create(name='foo')
        with self.login_user_context(self.user):
            url = reverse('admin:filer-ajax_upload', kwargs={'folder_id': folder.pk})
            post_data = {
                'jsessionid': self.client.session.session_key
            }
            response = self.client.post(url, post_data)
            self.assertEqual(response.status_code, 500)
            self.assertTrue(force_text(response.content).find('AJAX request not valid') > -1)
meta.py 文件源码 项目:drf-metadata 作者: night-crawler 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def format_choices(field: models.Field):
        for choice in field.choices:
            printable_name = force_text(choice[1])
            yield [choice[0], printable_name]
backend.py 文件源码 项目:wagtail-pg-search-backend 作者: wagtail 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def prepare_value(self, value):
        if isinstance(value, string_types):
            return value
        if isinstance(value, list):
            return ', '.join(self.prepare_value(item) for item in value)
        if isinstance(value, dict):
            return ', '.join(self.prepare_value(item)
                             for item in value.values())
        return force_text(value)
backend.py 文件源码 项目:wagtail-pg-search-backend 作者: wagtail 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def add_items(self, model, objs):
        content_type_pk = get_content_types_pks((model,), self.db_alias)[0]
        config = self.get_config()
        for obj in objs:
            obj._object_id = force_text(obj.pk)
            obj._body_ = self.prepare_body(obj)
        connection = connections[self.db_alias]
        if connection.pg_version >= 90500:  # PostgreSQL >= 9.5
            self.add_items_upsert(connection, content_type_pk, objs, config)
        else:
            self.add_items_update_then_create(content_type_pk, objs, config)


问题


面经


文章

微信
公众号

扫码关注公众号