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


Python http.urlquote方法代码示例

本文整理汇总了Python中django.utils.http.urlquote方法的典型用法代码示例。如果您正苦于以下问题:Python http.urlquote方法的具体用法?Python http.urlquote怎么用?Python http.urlquote使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.http的用法示例。


在下文中一共展示了http.urlquote方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: render

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def render(self, context):
        try:
            expire_time = self.expire_time_var.resolve(context)
        except VariableDoesNotExist:
            raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var)
        try:
            expire_time = int(expire_time)
        except (ValueError, TypeError):
            raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
        # Build a key for this fragment and all vary-on's.
        key = ':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])
        args = hashlib.md5(force_bytes(key))
        cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())
        value = cache.get(cache_key)
        if value is None:
            value = self.nodelist.render(context)
            cache.set(cache_key, value, expire_time)
        return value 
开发者ID:blackye,项目名称:luscan-devel,代码行数:20,代码来源:cache.py

示例2: __call__

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def __call__(self, request):
        if request.user.is_authenticated:
            profile = request.profile = request.user.profile
            logout_path = reverse('auth_logout')
            login_2fa_path = reverse('login_2fa')
            webauthn_path = reverse('webauthn_assert')
            change_password_path = reverse('password_change')
            change_password_done_path = reverse('password_change_done')
            has_2fa = profile.is_totp_enabled or profile.is_webauthn_enabled
            if (has_2fa and not request.session.get('2fa_passed', False) and
                    request.path not in (login_2fa_path, logout_path, webauthn_path) and
                    not request.path.startswith(settings.STATIC_URL)):
                return HttpResponseRedirect(login_2fa_path + '?next=' + urlquote(request.get_full_path()))
            elif (request.session.get('password_pwned', False) and
                    request.path not in (change_password_path, change_password_done_path,
                                         login_2fa_path, logout_path) and
                    not request.path.startswith(settings.STATIC_URL)):
                return HttpResponseRedirect(change_password_path + '?next=' + urlquote(request.get_full_path()))
        else:
            request.profile = None
        return self.get_response(request) 
开发者ID:DMOJ,项目名称:online-judge,代码行数:23,代码来源:middleware.py

示例3: test_get

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def test_get(self):
        """
        This tests that the view responds correctly for a user with edit permissions on this image
        """
        # Get
        response = self.client.get(reverse('wagtailimages:generate_url', args=(self.image.id, 'fill-800x600')))

        # Check response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')

        # Check JSON
        content_json = json.loads(response.content.decode())

        self.assertEqual(set(content_json.keys()), set(['url', 'preview_url']))

        expected_url = 'http://localhost/images/%(signature)s/%(image_id)d/fill-800x600/' % {
            'signature': urlquote(generate_signature(self.image.id, 'fill-800x600'), safe=urlquote_safechars),
            'image_id': self.image.id,
        }
        self.assertEqual(content_json['url'], expected_url)

        expected_preview_url = reverse('wagtailimages:preview', args=(self.image.id, 'fill-800x600'))
        self.assertEqual(content_json['preview_url'], expected_preview_url) 
开发者ID:wagtail,项目名称:wagtail,代码行数:26,代码来源:test_admin_views.py

示例4: create

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def create(request):
    if request.user.is_authenticated() and not request.user.is_anonymous():
        return redirect('/user/' + request.user.username + '/')
    if request.method == "POST":
        form = forms.CreateUserForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
            preferences = models.UserPreferences.objects.create(user=user)
            login(request, user)
            return redirect('/addaccount/' + ('?next=' + urlquote(request.GET['next']) if 'next' in request.GET else ''))
    else:
        form = forms.CreateUserForm()
    context = globalContext(request)
    context['form'] = form
    context['current'] = 'create'
    context['next'] = request.GET.get('next', None)
    return render(request, 'create.html', context) 
开发者ID:MagiCircles,项目名称:SchoolIdolAPI,代码行数:20,代码来源:views.py

示例5: addaccount

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def addaccount(request):
    if not request.user.is_authenticated() or request.user.is_anonymous():
        raise PermissionDenied()
    if request.method == "POST":
        form = forms.AccountForm(request.POST)
        if form.is_valid():
            account = form.save(commit=False)
            next_url = lambda account: '/cards/initialsetup/?account=' + str(account.id) + ('&starter=' + str(account.center_id) if account.center_id else '&starter=0') + ('&next=' + urlquote(request.GET['next']) if 'next' in request.GET else '')
            account.owner = request.user
            if account.rank >= 200:
                account.rank = 195
                account.save()
                _addaccount_savecenter(account)
                return redirect(next_url(account) + '&notification=ADDACCOUNTRANK200&notification_link_variables=' + str(account.pk))
            account.save()
            _addaccount_savecenter(account)
            return redirect(next_url(account))
    else:
        form = forms.AccountForm(initial={
            'nickname': request.user.username
        })
    context = globalContext(request)
    context['form'] = form
    context['current'] = 'addaccount'
    return render(request, 'addaccount.html', context) 
开发者ID:MagiCircles,项目名称:SchoolIdolAPI,代码行数:27,代码来源:views.py

示例6: test_container_html

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def test_container_html(self):
        self._test_html_content(
            self.child_container,
            expected_section_tag=(
                '<section class="wrapper-xblock level-page is-hidden studio-xblock-wrapper" '
                'data-locator="{0}" data-course-key="{0.course_key}">'.format(self.child_container.location)
            ),
            expected_breadcrumbs=(
                r'<a href="/course/{course}{section_parameters}" class="{classes}">\s*Week 1\s*</a>\s*'
                r'<a href="/course/{course}{subsection_parameters}" class="{classes}">\s*Lesson 1\s*</a>\s*'
                r'<a href="/container/{unit}" class="{classes}">\s*Unit\s*</a>'
            ).format(
                course=re.escape(unicode(self.course.id)),
                unit=re.escape(unicode(self.vertical.location)),
                classes='navigation-item navigation-link navigation-parent',
                section_parameters=re.escape(u'?show={}'.format(http.urlquote(self.chapter.location))),
                subsection_parameters=re.escape(u'?show={}'.format(http.urlquote(self.sequential.location))),
            ),
        ) 
开发者ID:jruiperezv,项目名称:ANALYSE,代码行数:21,代码来源:test_container_page.py

示例7: encode_filename

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def encode_filename(filename):
    """
    Encodes filename part for ``Content-Disposition: attachment``.

    >>> print(encode_filename("abc.pdf"))
    filename=abc.pdf
    >>> print(encode_filename("aa bb.pdf"))
    filename*=UTF-8''aa%20bb.pdf
    >>> print(encode_filename(u"zażółć.pdf"))
    filename*=UTF-8''za%C5%BC%C3%B3%C5%82%C4%87.pdf
    """
    # TODO: http://greenbytes.de/tech/webdav/rfc6266.html
    # TODO: http://greenbytes.de/tech/tc2231/

    quoted = urlquote(filename)
    if quoted == filename:
        return "filename=%s" % filename
    else:
        return "filename*=UTF-8''%s" % quoted 
开发者ID:nigma,项目名称:django-easy-pdf,代码行数:21,代码来源:rendering.py

示例8: proxy_url

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def proxy_url(url):
    url_parts = url.split(":")
    if len(url_parts) > 1:
        # check to see if the second item is a port number
        try:
            port = int(url_parts[1], 10)
        except ValueError:
            # second part of url was not a port
            port = 0

        # if the second part of a url is not a port, then we can assume the
        # first must be a protocol scheme
        if port == 0 and url_parts[0] not in ALLOW_URL_SCHEMES:
            # url starts with a protocol, but it's not one that we can redirect
            # to safely
            return url

    proxy = reverse("redirect")
    url = urlquote(url)
    return "{proxy}?url={url}".format(proxy=proxy, url=url) 
开发者ID:Inboxen,项目名称:Inboxen,代码行数:22,代码来源:__init__.py

示例9: get_context

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def get_context(self):
        new_context = {
            'title': self.get_title(),
            'icon': self.icon,
            'portal_key': self.get_portal_key(),
            'columns': [('col-sm-%d' % int(12 / len(self.widgets)), ws) for ws in self.widgets],
            'has_add_widget_permission': self.has_model_perm(UserWidget, 'add') and self.widget_customiz,
            'add_widget_url': self.get_admin_url('%s_%s_add' % (UserWidget._meta.app_label, UserWidget._meta.model_name)) +
            "?user=%s&page_id=%s&_redirect=%s" % (self.user.id, self.get_page_id(), urlquote(self.request.get_full_path()))
        }
        context = super(Dashboard, self).get_context()
        context.update(new_context)
        return context 
开发者ID:stormsha,项目名称:StormOnline,代码行数:15,代码来源:dashboard.py

示例10: review_registration

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def review_registration(self, request, object_id):
        reg = get_object_or_404(Registration, pk=object_id)
        if not request.user.has_perm('tournament.change_registration', reg.season.league):
            raise PermissionDenied

        if request.method == 'POST':
            changelist_filters = request.POST.get('_changelist_filters', '')
            form = forms.ReviewRegistrationForm(request.POST)
            if form.is_valid():
                params = '?_changelist_filters=' + urlquote(changelist_filters)
                if 'approve' in form.data and reg.status == 'pending':
                    return redirect_with_params('admin:approve_registration', object_id=object_id,
                                                params=params)
                elif 'reject' in form.data and reg.status == 'pending':
                    return redirect_with_params('admin:reject_registration', object_id=object_id,
                                                params=params)
                elif 'edit' in form.data:
                    return redirect_with_params('admin:tournament_registration_change', object_id,
                                                params=params)
                else:
                    return redirect_with_params('admin:tournament_registration_changelist',
                                                params=params)
        else:
            changelist_filters = request.GET.get('_changelist_filters', '')
            form = forms.ReviewRegistrationForm()

        is_team = reg.season.league.competitor_type == 'team'

        context = {
            'has_permission': True,
            'opts': self.model._meta,
            'site_url': '/',
            'original': reg,
            'title': 'Review registration',
            'form': form,
            'is_team': is_team,
            'changelist_filters': changelist_filters
        }

        return render(request, 'tournament/admin/review_registration.html', context) 
开发者ID:cyanfish,项目名称:heltour,代码行数:42,代码来源:admin.py

示例11: review_request

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def review_request(self, request, object_id):
        obj = get_object_or_404(ModRequest, pk=object_id)
        if not request.user.has_perm('tournament.change_modrequest', obj.season.league):
            raise PermissionDenied

        if request.method == 'POST':
            changelist_filters = request.POST.get('_changelist_filters', '')
            form = forms.ReviewModRequestForm(request.POST)
            if form.is_valid():
                params = '?_changelist_filters=' + urlquote(changelist_filters)
                if 'approve' in form.data and obj.status == 'pending':
                    return redirect_with_params('admin:tournament_modrequest_approve',
                                                object_id=object_id, params=params)
                elif 'reject' in form.data and obj.status == 'pending':
                    return redirect_with_params('admin:tournament_modrequest_reject',
                                                object_id=object_id, params=params)
                elif 'edit' in form.data:
                    return redirect_with_params('admin:tournament_modrequest_change', object_id,
                                                params=params)
                else:
                    return redirect_with_params('admin:tournament_modrequest_changelist',
                                                params=params)
        else:
            changelist_filters = request.GET.get('_changelist_filters', '')
            form = forms.ReviewModRequestForm()

        context = {
            'has_permission': True,
            'opts': self.model._meta,
            'site_url': '/',
            'original': obj,
            'title': 'Review mod request',
            'form': form,
            'changelist_filters': changelist_filters
        }

        return render(request, 'tournament/admin/review_modrequest.html', context) 
开发者ID:cyanfish,项目名称:heltour,代码行数:39,代码来源:admin.py

示例12: approve_request

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def approve_request(self, request, object_id):
        obj = get_object_or_404(ModRequest, pk=object_id)
        if not request.user.has_perm('tournament.change_modrequest', obj.season.league):
            raise PermissionDenied

        if obj.status != 'pending':
            return redirect('admin:tournament_modrequest_review', object_id)

        if request.method == 'POST':
            changelist_filters = request.POST.get('_changelist_filters', '')
            form = forms.ApproveModRequestForm(request.POST)
            if form.is_valid():
                if 'confirm' in form.data:
                    obj.approve(request.user.username, form.cleaned_data['response'])
                    self.message_user(request, 'Request approved.', messages.INFO)
                    return redirect_with_params('admin:tournament_modrequest_changelist',
                                                params='?' + changelist_filters)
                else:
                    return redirect_with_params('admin:tournament_modrequest_review', object_id,
                                                params='?_changelist_filters=' + urlquote(
                                                    changelist_filters))
        else:
            changelist_filters = request.GET.get('_changelist_filters', '')
            form = forms.ApproveModRequestForm()

        context = {
            'has_permission': True,
            'opts': self.model._meta,
            'site_url': '/',
            'original': obj,
            'title': 'Confirm approval',
            'form': form,
            'changelist_filters': changelist_filters
        }

        return render(request, 'tournament/admin/approve_modrequest.html', context) 
开发者ID:cyanfish,项目名称:heltour,代码行数:38,代码来源:admin.py

示例13: urlencode

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def urlencode(value, safe=None):
    """
    Escapes a value for use in a URL.

    Takes an optional ``safe`` parameter used to determine the characters which
    should not be escaped by Django's ``urlquote`` method. If not provided, the
    default safe characters will be used (but an empty string can be provided
    when *all* characters should be escaped).
    """
    kwargs = {}
    if safe is not None:
        kwargs['safe'] = safe
    return urlquote(value, **kwargs) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:15,代码来源:defaultfilters.py

示例14: make_template_fragment_key

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def make_template_fragment_key(fragment_name, vary_on=None):
    if vary_on is None:
        vary_on = ()
    key = ':'.join(urlquote(var) for var in vary_on)
    args = hashlib.md5(force_bytes(key))
    return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest()) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:8,代码来源:utils.py

示例15: export_config

# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import urlquote [as 别名]
def export_config(request):
    """
    导出配置
    :param request:
    :return:
    """
    try:
        file_name = 'export_config_%s.json' % datetime.today().strftime('%Y%m%d')
        json_data = get_export_config_json()
        config_data = json_dumps(json_data, indent=4, sort_keys=True)

        agent = request.META.get('HTTP_USER_AGENT')
        if agent and re.search('MSIE', agent):
            # 解决ie不能下载的问题
            response = HttpResponse(content=config_data, content_type="text/plain; charset=utf-8")
            # 解决文件名乱码/不显示的问题
            response['Content-Disposition'] = 'attachment; filename=%s' % urlquote(file_name)
        else:
            response = HttpResponse(content=config_data, content_type="text/plain; charset=utf-8")
            response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)

        return response
    except Exception as e:
        logger.error(e.message)
        logger.error(traceback.format_exc())
        return HttpResponse('导出配置失败 %s' % e.message) 
开发者ID:restran,项目名称:fomalhaut-panel,代码行数:28,代码来源:views.py


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