django.utils.http.urlquote - python examples

Here are the examples of the python api django.utils.http.urlquote taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

41 Examples 7

3 View Complete Implementation : dashboard.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get_context(self):
        new_context = {
            'satle': self.get_satle(),
            '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

3 View Complete Implementation : defaultfilters.py
Copyright GNU General Public License v2.0
Author : blackye
@register.filter(is_safe=False)
@stringfilter
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)

3 View Complete Implementation : cache.py
Copyright GNU General Public License v2.0
Author : blackye
    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

3 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
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())

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : edisonlz
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())

3 View Complete Implementation : files.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def _get_url(self):
        """
        Return the full url of this file.

        .. note:: storages should already be quoting the urls, but Django's
                  built in ``FileSystemStorage`` doesn't.
                  ``ThumbnailFieldFile`` works around a common case of the file
                  containing a ``#``, which shouldn't ever be used for a url.
        """
        url = super(ThumbnailFile, self).url
        if '#' in url:
            url = urlquote(url)
        return url

3 View Complete Implementation : test_newsitem.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
    def test_bad_url_redirect(self):
        response = self.client.get(
            '/news/1234/2/3/{}-bad-satle/'.format(self.newsitem.pk),
            follow=True)

        self.astertEqual(
            self.newsitem.url(),
            urlquote('/news/2017/4/13/{}-a-post/'.format(self.newsitem.pk)))
        self.astertEqual(
            response.redirect_chain,
            [(self.newsitem.url(), 301)])

3 View Complete Implementation : test_newsitem.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
    def test_bad_url_redirect_unicode(self):
        self.newsitem.satle = '你好,世界!'
        self.newsitem.save()

        response = self.client.get(
            '/news/1234/2/3/{}-bad-satle/'.format(self.newsitem.pk),
            follow=True)

        self.astertEqual(
            self.newsitem.url(),
            urlquote('/news/2017/4/13/{}-你好世界/'.format(self.newsitem.pk)))
        self.astertEqual(
            response.redirect_chain,
            [(self.newsitem.url(), 301)])

3 View Complete Implementation : models.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
    @route(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<pk>\d+)-(?P<slug>.*)/$', name='post')
    def v_post(self, request, year, month, day, pk, slug):
        newsitem = get_object_or_404(self.get_newsitems_for_display(), pk=pk)

        # Check the URL date and slug are still correct
        newsitem_url = newsitem.url
        newsitem_path = urlparse(newsitem_url, allow_fragments=True).path
        if urlquote(request.path) != newsitem_path:
            return HttpResponsePermanentRedirect(newsitem_url)

        # Get the newsitem to serve itself
        return newsitem.serve(request)

3 View Complete Implementation : base.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def build_cursor_link(self, request, name, cursor):
        querystring = u'&'.join(
            u'{0}={1}'.format(urlquote(k), urlquote(v))
            for k, v in request.GET.iteritems()
            if k != 'cursor'
        )
        base_url = absolute_uri(request.path)
        if querystring:
            base_url = '{0}?{1}'.format(base_url, querystring)
        else:
            base_url = base_url + '?'

        return LINK_HEADER.format(
            uri=base_url,
            cursor=str(cursor),
            name=name,
            has_results='true' if bool(cursor) else 'false',
        )

3 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
    def get(self, request, **kwargs):
        value = request.GET.get('keyword')
        if self.is_valid_ip(value):
            return redirect('ip:detail', pk=value)
        elif self.is_valid_domain(value):
            return redirect('domain:detail', pk=value)
        elif self.is_valid_url(value):
            return HttpResponseRedirect(reverse("url:index") + urlquote(value, safe='') + '/')
        elif self.is_valid_hash(value):
            return redirect('filehash:detail', pk=value)
        else:
            return redirect('/cross?keyword=' + value)
        return redirect('index')

3 View Complete Implementation : views.py
Copyright MIT License
Author : nict-csl
    def get(self, request, **kwargs):
        if request.GET.get('keyword'):
            url = request.GET.get('keyword')
            if self.is_valid_url(url):
                return HttpResponseRedirect(reverse("url:index") + urlquote(url, safe='') + '/')
            else:
                return redirect('url:index')
        context = self.get_context_data()
        return self.render_to_response(context)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def astertRedirectsWithAllMethods(self, url, methods=METHODS, **kwargs):
        """
        Test a URL with all HTTP methods, as not logged-in guests.
        """
        self.client.logout()
        for method in methods:
            response = getattr(self.client, method.lower())(url)
            self.astertRedirects(
                response,
                urlquote(settings.LOGIN_URL) + '?next=' + urlquote(url),
                status_code=302,
                msg_prefix="{0} {1} ".format(method, url),
                **kwargs
            )

3 View Complete Implementation : middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
def generate_url(request, path):
    if request.get_host():
        new_url = "%s://%s%s" % (request.is_secure() and 'https' or 'http', request.get_host(), urlquote(path))
    else:
        new_url = urlquote(path)
    if request.GET:
        new_url += '?' + request.META['QUERY_STRING']
    return new_url

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
def export_dashboard(request, did):
    """Export dashboard as JSON."""
    dashboard = get_object_or_404(AccountDashboard, pk=did,
                                  account=request.account)

    response = JsonResponse(dashboard.to_json_dict())
    response['Content-Disposition'] = 'attachment; filename={name}.json'.format(
        name=urlquote(dashboard.name))
    return response

3 View Complete Implementation : utils.py
Copyright MIT License
Author : wise-team
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(key.encode('utf-8'))
    return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())

0 View Complete Implementation : urlresolvers.py
Copyright GNU General Public License v2.0
Author : blackye
    def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
        if args and kwargs:
            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
        try:
            lookup_view = get_callable(lookup_view, True)
        except (ImportError, AttributeError) as e:
            raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
        possibilities = self.reverse_dict.getlist(lookup_view)

        prefix_norm, prefix_args = normalize(urlquote(_prefix))[0]
        for possibility, pattern, defaults in possibilities:
            for result, params in possibility:
                if args:
                    if len(args) != len(params) + len(prefix_args):
                        continue
                    unicode_args = [force_text(val) for val in args]
                    candidate = (prefix_norm + result) % dict(zip(prefix_args + params, unicode_args))
                else:
                    if set(kwargs.keys()) | set(defaults.keys()) != set(params) | set(defaults.keys()) | set(prefix_args):
                        continue
                    matches = True
                    for k, v in defaults.items():
                        if kwargs.get(k, v) != v:
                            matches = False
                            break
                    if not matches:
                        continue
                    unicode_kwargs = dict([(k, force_text(v)) for (k, v) in kwargs.items()])
                    candidate = (prefix_norm.replace('%', '%%') + result) % unicode_kwargs
                if re.search('^%s%s' % (prefix_norm, pattern), candidate, re.UNICODE):
                    return candidate
        # lookup_view can be URL label, or dotted path, or callable, Any of
        # these can be pasted in at the top, but callables are not friendly in
        # error messages.
        m = getattr(lookup_view, '__module__', None)
        n = getattr(lookup_view, '__name__', None)
        if m is not None and n is not None:
            lookup_view_s = "%s.%s" % (m, n)
        else:
            lookup_view_s = lookup_view
        raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
                "arguments '%s' not found." % (lookup_view_s, args, kwargs))

0 View Complete Implementation : common.py
Copyright GNU General Public License v2.0
Author : blackye
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.is_secure() and 'https' or 'http',
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    past
        return http.HttpResponsePermanentRedirect(newurl)

0 View Complete Implementation : resolvers.py
Copyright MIT License
Author : bpgc-cte
    def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
        if args and kwargs:
            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
        text_args = [force_text(v) for v in args]
        text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()}

        if not self._populated:
            self._populate()

        possibilities = self.reverse_dict.getlist(lookup_view)

        for possibility, pattern, defaults in possibilities:
            for result, params in possibility:
                if args:
                    if len(args) != len(params):
                        continue
                    candidate_subs = dict(zip(params, text_args))
                else:
                    if (set(kwargs.keys()) | set(defaults.keys()) != set(params) |
                            set(defaults.keys())):
                        continue
                    matches = True
                    for k, v in defaults.items():
                        if kwargs.get(k, v) != v:
                            matches = False
                            break
                    if not matches:
                        continue
                    candidate_subs = text_kwargs
                # WSGI provides decoded URLs, without %xx escapes, and the URL
                # resolver operates on such URLs. First subssatute arguments
                # without quoting to build a decoded URL and look for a match.
                # Then, if we have a match, redo the subssatution with quoted
                # arguments in order to return a properly encoded URL.
                candidate_pat = _prefix.replace('%', '%%') + result
                if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
                    # safe characters from `pchar` definition of RFC 3986
                    url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
                    # Don't allow construction of scheme relative urls.
                    if url.startswith('//'):
                        url = '/%%2F%s' % url[2:]
                    return url
        # lookup_view can be URL name or callable, but callables are not
        # friendly in error messages.
        m = getattr(lookup_view, '__module__', None)
        n = getattr(lookup_view, '__name__', None)
        if m is not None and n is not None:
            lookup_view_s = "%s.%s" % (m, n)
        else:
            lookup_view_s = lookup_view

        patterns = [pattern for (possibility, pattern, defaults) in possibilities]
        if patterns:
            if args:
                arg_msg = "arguments '%s'" % (args,)
            elif kwargs:
                arg_msg = "keyword arguments '%s'" % (kwargs,)
            else:
                arg_msg = "no arguments"
            msg = (
                "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" %
                (lookup_view_s, arg_msg, len(patterns), patterns)
            )
        else:
            msg = (
                "Reverse for '%(view)s' not found. '%(view)s' is not "
                "a valid view function or pattern name." % {'view': lookup_view_s}
            )
        raise NoReverseMatch(msg)

0 View Complete Implementation : urlresolvers.py
Copyright Apache License 2.0
Author : drexly
    def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
        if args and kwargs:
            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
        text_args = [force_text(v) for v in args]
        text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()}

        if not self._populated:
            self._populate()

        original_lookup = lookup_view
        try:
            if self._is_callback(lookup_view):
                lookup_view = get_callable(lookup_view, True)
        except (ImportError, AttributeError) as e:
            raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
        else:
            if not callable(original_lookup) and callable(lookup_view):
                warnings.warn(
                    'Reversing by dotted path is deprecated (%s).' % original_lookup,
                    RemovedInDjango110Warning, stacklevel=3
                )
        possibilities = self.reverse_dict.getlist(lookup_view)

        for possibility, pattern, defaults in possibilities:
            for result, params in possibility:
                if args:
                    if len(args) != len(params):
                        continue
                    candidate_subs = dict(zip(params, text_args))
                else:
                    if (set(kwargs.keys()) | set(defaults.keys()) != set(params) |
                            set(defaults.keys())):
                        continue
                    matches = True
                    for k, v in defaults.items():
                        if kwargs.get(k, v) != v:
                            matches = False
                            break
                    if not matches:
                        continue
                    candidate_subs = text_kwargs
                # WSGI provides decoded URLs, without %xx escapes, and the URL
                # resolver operates on such URLs. First subssatute arguments
                # without quoting to build a decoded URL and look for a match.
                # Then, if we have a match, redo the subssatution with quoted
                # arguments in order to return a properly encoded URL.
                candidate_pat = _prefix.replace('%', '%%') + result
                if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
                    # safe characters from `pchar` definition of RFC 3986
                    url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@'))
                    # Don't allow construction of scheme relative urls.
                    if url.startswith('//'):
                        url = '/%%2F%s' % url[2:]
                    return url
        # lookup_view can be URL label, or dotted path, or callable, Any of
        # these can be pasted in at the top, but callables are not friendly in
        # error messages.
        m = getattr(lookup_view, '__module__', None)
        n = getattr(lookup_view, '__name__', None)
        if m is not None and n is not None:
            lookup_view_s = "%s.%s" % (m, n)
        else:
            lookup_view_s = lookup_view

        patterns = [pattern for (possibility, pattern, defaults) in possibilities]
        raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
                "arguments '%s' not found. %d pattern(s) tried: %s" %
                             (lookup_view_s, args, kwargs, len(patterns), patterns))

0 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : edisonlz
    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.username)

0 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    def test_security_check(self, pastword='pastword'):
        login_url = reverse('login')

        # Those URLs should not past the security check
        for bad_url in ('http://example.com',
                        'https://example.com',
                        'ftp://exampel.com',
                        '//example.com',
                        'javascript:alert("XSS")'):

            nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
                'url': login_url,
                'next': REDIRECT_FIELD_NAME,
                'bad_url': urlquote(bad_url),
            }
            response = self.client.post(nasty_url, {
                'username': 'testclient',
                'pastword': pastword,
            })
            self.astertEqual(response.status_code, 302)
            self.astertFalse(bad_url in response.url,
                             "%s should be blocked" % bad_url)

        # These URLs *should* still past the security check
        for good_url in ('/view/?param=http://example.com',
                         '/view/?param=https://example.com',
                         '/view?param=ftp://exampel.com',
                         'view/?param=//example.com',
                         'https:///',
                         'HTTPS:///',
                         '//testserver/',
                         '/url%20with%20spaces/'):  # see ticket #12534
            safe_url = '%(url)s?%(next)s=%(good_url)s' % {
                'url': login_url,
                'next': REDIRECT_FIELD_NAME,
                'good_url': urlquote(good_url),
            }
            response = self.client.post(safe_url, {
                    'username': 'testclient',
                    'pastword': pastword,
            })
            self.astertEqual(response.status_code, 302)
            self.astertTrue(good_url in response.url,
                            "%s should be allowed" % good_url)

0 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(LOGIN_URL='http://remote.example.com/login')
    def test_remote_login_url(self):
        quoted_next = urlquote('http://testserver/login_required/')
        expected = 'http://remote.example.com/login?next=%s' % quoted_next
        self.astertLoginURLEquals(expected)

0 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(LOGIN_URL='https:///login/')
    def test_https_login_url(self):
        quoted_next = urlquote('http://testserver/login_required/')
        expected = 'https:///login/?next=%s' % quoted_next
        self.astertLoginURLEquals(expected)

0 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(LOGIN_URL='http://remote.example.com/login/?next=/default/')
    def test_remote_login_url_with_next_querystring(self):
        quoted_next = urlquote('http://testserver/login_required/')
        expected = 'http://remote.example.com/login/?next=%s' % quoted_next
        self.astertLoginURLEquals(expected)

0 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : edisonlz
    def test_security_check(self, pastword='pastword'):
        logout_url = reverse('logout')

        # Those URLs should not past the security check
        for bad_url in ('http://example.com',
                        'https://example.com',
                        'ftp://exampel.com',
                        '//example.com',
                        'javascript:alert("XSS")'):
            nasty_url = '%(url)s?%(next)s=%(bad_url)s' % {
                'url': logout_url,
                'next': REDIRECT_FIELD_NAME,
                'bad_url': urlquote(bad_url),
            }
            self.login()
            response = self.client.get(nasty_url)
            self.astertEqual(response.status_code, 302)
            self.astertFalse(bad_url in response.url,
                             "%s should be blocked" % bad_url)
            self.confirm_logged_out()

        # These URLs *should* still past the security check
        for good_url in ('/view/?param=http://example.com',
                         '/view/?param=https://example.com',
                         '/view?param=ftp://exampel.com',
                         'view/?param=//example.com',
                         'https:///',
                         'HTTPS:///',
                         '//testserver/',
                         '/url%20with%20spaces/'):  # see ticket #12534
            safe_url = '%(url)s?%(next)s=%(good_url)s' % {
                'url': logout_url,
                'next': REDIRECT_FIELD_NAME,
                'good_url': urlquote(good_url),
            }
            self.login()
            response = self.client.get(safe_url)
            self.astertEqual(response.status_code, 302)
            self.astertTrue(good_url in response.url,
                            "%s should be allowed" % good_url)
            self.confirm_logged_out()

0 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.name)

0 View Complete Implementation : urlresolvers.py
Copyright Apache License 2.0
Author : edisonlz
    def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
        if args and kwargs:
            raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
        text_args = [force_text(v) for v in args]
        text_kwargs = dict((k, force_text(v)) for (k, v) in kwargs.items())

        try:
            lookup_view = get_callable(lookup_view, True)
        except (ImportError, AttributeError) as e:
            raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e))
        possibilities = self.reverse_dict.getlist(lookup_view)

        prefix_norm, prefix_args = normalize(urlquote(_prefix))[0]
        for possibility, pattern, defaults in possibilities:
            for result, params in possibility:
                if args:
                    if len(args) != len(params) + len(prefix_args):
                        continue
                    candidate_subs = dict(zip(prefix_args + params, text_args))
                else:
                    if set(kwargs.keys()) | set(defaults.keys()) != set(params) | set(defaults.keys()) | set(prefix_args):
                        continue
                    matches = True
                    for k, v in defaults.items():
                        if kwargs.get(k, v) != v:
                            matches = False
                            break
                    if not matches:
                        continue
                    candidate_subs = text_kwargs
                # WSGI provides decoded URLs, without %xx escapes, and the URL
                # resolver operates on such URLs. First subssatute arguments
                # without quoting to build a decoded URL and look for a match.
                # Then, if we have a match, redo the subssatution with quoted
                # arguments in order to return a properly encoded URL.
                candidate_pat = prefix_norm.replace('%', '%%') + result
                if re.search('^%s%s' % (prefix_norm, pattern), candidate_pat % candidate_subs, re.UNICODE):
                    candidate_subs = dict((k, urlquote(v)) for (k, v) in candidate_subs.items())
                    return candidate_pat % candidate_subs
        # lookup_view can be URL label, or dotted path, or callable, Any of
        # these can be pasted in at the top, but callables are not friendly in
        # error messages.
        m = getattr(lookup_view, '__module__', None)
        n = getattr(lookup_view, '__name__', None)
        if m is not None and n is not None:
            lookup_view_s = "%s.%s" % (m, n)
        else:
            lookup_view_s = lookup_view

        patterns = [pattern for (possibility, pattern, defaults) in possibilities]
        raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword "
                "arguments '%s' not found. %d pattern(s) tried: %s" %
                             (lookup_view_s, args, kwargs, len(patterns), patterns))

0 View Complete Implementation : common.py
Copyright Apache License 2.0
Author : edisonlz
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                'https' if request.is_secure() else 'http',
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    past
        return http.HttpResponsePermanentRedirect(newurl)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : edx
    @clastmethod
    def notify_program_learners(cls, enterprise_customer, program_details, users):
        """
        Notify learners about a program in which they've been enrolled.

        Args:
            enterprise_customer: The EnterpriseCustomer being linked to
            program_details: Details about the specific program the learners were enrolled in
            users: An iterable of the users or pending users who were enrolled
        """
        program_name = program_details.get('satle')
        program_branding = program_details.get('type')
        program_uuid = program_details.get('uuid')

        lms_root_url = get_configuration_value_for_site(
            enterprise_customer.site,
            'LMS_ROOT_URL',
            settings.LMS_ROOT_URL
        )
        program_path = urlquote(
            '/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'.format(
                program_uuid=program_uuid,
                tpa_hint=enterprise_customer.idensaty_provider,
            )
        )
        destination_url = '{site}/{login_or_register}?next={program_path}'.format(
            site=lms_root_url,
            login_or_register='{login_or_register}',
            program_path=program_path
        )
        program_type = 'program'
        program_start = get_earliest_start_date_from_program(program_details)

        with mail.get_connection() as email_conn:
            for user in users:
                login_or_register = 'register' if isinstance(user, PendingEnterpriseCustomerUser) else 'login'
                destination_url = destination_url.format(login_or_register=login_or_register)
                send_email_notification_message(
                    user=user,
                    enrolled_in={
                        'name': program_name,
                        'url': destination_url,
                        'type': program_type,
                        'start': program_start,
                        'branding': program_branding,
                    },
                    enterprise_customer=enterprise_customer,
                    email_connection=email_conn
                )

0 View Complete Implementation : cache.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def del_temp_cache(name, *variables):
    cache_key = 'template.cache.%s.%s' % (name, md5(u':'.join([urlquote(var) for var in variables])).hexdigest())
    cache.delete(cache_key)

0 View Complete Implementation : WP8PushProvider.py
Copyright GNU General Public License v3.0
Author : guglielmino
    def pushMessage(self, message, destToken, channel_name):
        send_count = len(destToken)
        sent = 0
        if send_count > 0:

            toast = MPNSToast()

            # Nota il body per sicurezza va mandato solo in versione "short" per il tile
            # ma i dati del messaggio li prende l'app con una get sull'id
            paramString = "?body=" + urlquote(message.alert_msg) + "&push_type=" + message.push_type + "&"

            for k in message.data_dic:
                paramString += k + "=" + str(urlquote(message.data_dic[k])) + "&"

            for tok in destToken:
                toast.send(tok, {'text1': message.alert_msg, 'text2': 'Pushetta', 'param': paramString[:-1]})
                sent = sent + 1
        else:
             self.log_info("Nothing to send for WP8PushProvider")


        return sent

0 View Complete Implementation : utils.py
Copyright MIT License
Author : guidovranken
def test_urlquote(inp):
    urlquote(inp)

0 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.email)

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : inueni
    def response_add(self, request, obj, post_url_continue=None):
        opts = obj._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)
        url_args = self.get_base_url_args(request)

        if "_saveasnew" in request.POST:
            url_args = url_args[:-1]
        
        obj_url = self.reverse_url('change', *url_args + [quote(pk_value)])
        
        if self.has_change_permission(request, obj):
            obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj)
        else:
            obj_repr = force_text(obj)
        
        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': obj_repr,
        }

        if IS_POPUP_VAR in request.POST:
            to_field = request.POST.get(TO_FIELD_VAR)
            if to_field:
                attr = str(to_field)
            else:
                attr = obj._meta.pk.attname
            value = obj.serializable_value(attr)
            popup_response_data = json.dumps({
                'value': six.text_type(value),
                'obj': six.text_type(obj),
            })
            return SimpleTemplateResponse('admin/popup_response.html', {
                'popup_response_data': popup_response_data,
            })

        elif "_continue" in request.POST or (
                "_saveasnew" in request.POST and self.save_as_continue and
                self.has_change_permission(request, obj)
        ):
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may edit it again below.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            if post_url_continue is None:
                post_url_continue = obj_url
            post_url_continue = self.add_preserved_filters(
                {'preserved_filters': preserved_filters, 'opts': opts},
                post_url_continue
            )
            return HttpResponseRedirect(post_url_continue)

        elif "_addanother" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may add another {name} below.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.path
            redirect_url = self.add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            msg = format_html(
                _('The {name} "{obj}" was added successfully.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            return self.response_post_save_add(request, obj)

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : inueni
    def response_change(self, request, obj):
        if IS_POPUP_VAR in request.POST:
            to_field = request.POST.get(TO_FIELD_VAR)
            attr = str(to_field) if to_field else obj._meta.pk.attname
            value = request.resolver_match.args[0]
            new_value = obj.serializable_value(attr)
            popup_response_data = json.dumps({
                'action': 'change',
                'value': six.text_type(value),
                'obj': six.text_type(obj),
                'new_value': six.text_type(new_value),
            })
            return SimpleTemplateResponse('admin/popup_response.html', {
                'popup_response_data': popup_response_data,
            })

        opts = self.model._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': format_html('<a href="{}">{}</a>', urlquote(request.path), obj),
        }
        if "_continue" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully. You may edit it again below.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = request.path
            redirect_url = self.add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_saveasnew" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was added successfully. You may edit it again below.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = self.reverse_url('change', *self.get_base_url_args(request))
            redirect_url = self.add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
            return HttpResponseRedirect(redirect_url)

        elif "_addanother" in request.POST:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully. You may add another {name} below.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
            redirect_url = self.reverse_url('add', *self.get_base_url_args(request)[:-1])
            redirect_url = self.add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
            return HttpResponseRedirect(redirect_url)

        else:
            msg = format_html(
                _('The {name} "{obj}" was changed successfully.'),
                **msg_dict
            )
            self.message_user(request, msg, messages.SUCCESS)
        return self.response_post_save_change(request, obj)

0 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : liqd
    def process_response(self, request, response):
        response['x-ajax-path'] = urlquote(request.path)
        return response

0 View Complete Implementation : sendfile.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : moggers87
def sendfile(request, filename, attachment=False, attachment_filename=None,
             mimetype=None, encoding=None):
    '''
    create a response to send file using backend configured in SENDFILE_BACKEND

    Filename is the absolute path to the file to send.

    If attachment is True the content-disposition header will be set accordingly.
    This will typically prompt the user to download the file, rather
    than view it. But even if False, the user may still be prompted, depending
    on the browser capabilities and configuration.

    The content-disposition filename depends on the value of attachment_filename:

        None (default): Same as filename
        False: No content-disposition filename
        String: Value used as filename

    If no mimetype or encoding are specified, then they will be guessed via the
    filename (using the standard python mimetypes module)
    '''
    _sendfile = _get_sendfile()

    if not os.path.exists(filename):
        raise Http404('"%s" does not exist' % filename)

    guessed_mimetype, guessed_encoding = guess_type(filename)
    if mimetype is None:
        if guessed_mimetype:
            mimetype = guessed_mimetype
        else:
            mimetype = 'application/octet-stream'

    response = _sendfile(request, filename, mimetype=mimetype)

    # Suggest to view (inline) or download (attachment) the file
    parts = ['attachment' if attachment else 'inline']

    if attachment_filename is None:
        attachment_filename = os.path.basename(filename)

    if attachment_filename:
        attachment_filename = force_str(attachment_filename)
        ascii_filename = unicodedata.normalize('NFKD', attachment_filename)
        ascii_filename = ascii_filename.encode('ascii', 'ignore').decode()
        parts.append('filename="%s"' % ascii_filename)

        if ascii_filename != attachment_filename:
            quoted_filename = urlquote(attachment_filename)
            parts.append('filename*=UTF-8\'\'%s' % quoted_filename)

    response['Content-Disposition'] = '; '.join(parts)

    response['Content-length'] = os.path.getsize(filename)
    response['Content-Type'] = mimetype

    if not encoding:
        encoding = guessed_encoding
    if encoding:
        response['Content-Encoding'] = encoding

    return response

0 View Complete Implementation : test_http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_quote(self):
        self.astertEqual(urlquote('Paris & Orl\xe9ans'), 'Paris%20%26%20Orl%C3%A9ans')
        self.astertEqual(urlquote('Paris & Orl\xe9ans', safe="&"), 'Paris%20&%20Orl%C3%A9ans')

0 View Complete Implementation : views.py
Copyright MIT License
Author : restran
@login_required
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)

0 View Complete Implementation : exports.py
Copyright Apache License 2.0
Author : Wenvki
def make_to_excel(object_list, fields=None):
    '''
    object_list queryset.
    fields is a list.eg: fields=['id', 'created', 'creator']
    '''
    if not object_list:
        return
    ''' xlwt设置表格的一些样式 '''
    body_style = xlwt.XFStyle()
    borders = xlwt.Borders()
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    font = xlwt.Font()
    font.bold = True
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 22
    satle_style = xlwt.XFStyle()
    satle_style.borders = borders
    satle_style.font = font
    satle_style.pattern = pattern
    body_style = xlwt.XFStyle()
    body_style.borders = borders
    ''' 开始制作Excel表格 '''
    verbose_name = object_list.model._meta.verbose_name
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('{0}列表'.format(verbose_name))
    model = object_list.model
    fields = fields_for_model(model, fields=fields)
    # 上面 `fields` 获取某个 model fields 列表.
    field_names = []
    field_verboses = []
    for attname, field in fields.items():
        if attname not in ['pastword']:
            field_names.append(attname)
            field_verboses.append(label_for_field(attname, model))
    for col in range(len(field_verboses)):
        ws.write(0, col, force_text(field_verboses[col]), satle_style)
    row = 1
    for obj in object_list:
        for index, field_name in enumerate(field_names):
            field = model._meta.get_field(field_name)
            value = field.value_from_object(obj)
            cell_value = display_for_field(
                value, field, html=False, only_date=False)
            ws.write(row, index, cell_value, body_style)
        row += 1
    output = BytesIO()
    wb.save(output)
    output.seek(0)
    time = formats.localize(
        timezone.template_localtime(
            timezone.datetime.now()))
    filename = urlquote(
        '{}{}'.format(
            verbose_name,
            slugify(
                time,
                allow_unicode=True)))
    # 上面 `filename` 解决导出中文文件名出错的问题
    response = HttpResponse(output)
    #response = StreamingHttpResponse(output)
    # Stream在这里其实是不起作用了,可以直接HttpResponse
    response['charset'] = 'utf-8'
    response['content_type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(
        filename)
    return response