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.
139 Examples
3
Example 1
def redirect_if_necessary(self, current_path, category):
if self.enforce_paths:
# Categories are fetched by primary key to allow slug changes.
# If the slug has changed, issue a redirect.
expected_path = category.get_absolute_url()
if expected_path != urlquote(current_path):
return HttpResponsePermanentRedirect(expected_path)
3
Example 2
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).
"""
from django.utils.http import urlquote
kwargs = {}
if safe is not None:
kwargs['safe'] = safe
return urlquote(value, **kwargs)
3
Example 3
Project: django-adv-cache-tag Source File: tests.py
@staticmethod
def get_template_key(fragment_name, vary_on=None, prefix='template.cache'):
"""Compose the cache key of a template."""
if vary_on is None:
vary_on = ()
key = ':'.join([urlquote(var) for var in vary_on])
args = hashlib.md5(force_bytes(key))
return (prefix + '.%s.%s') % (fragment_name, args.hexdigest())
3
Example 4
def process_request(self, request):
if request.get_host() == self.canonical_hostname:
return
# Domains didn't match, so do some fixups.
new_url = [
'https' if request.is_secure() else 'http',
'://',
self.canonical_hostname,
urlquote(request.path),
'?%s' % request.GET.urlencode() if request.GET else ''
]
return redirect(''.join(new_url), permanent=True)
3
Example 5
def get_url(self, obj, view_name, request, format):
if obj.pk is None:
return None
lookup_value = getattr(obj, self.lookup_field)
quoted_lookup_value = django.utils.http.urlquote(lookup_value)
kwargs = {self.lookup_url_kwarg: quoted_lookup_value}
return self.reverse(
view_name, kwargs=kwargs, request=request, format=format)
3
Example 6
Project: transifex Source File: cache.py
def invalidate_template_cache(fragment_name, *variables):
"""This function invalidates a template cache.
The template cache is named `fragment_name` and the variables are
included in *variables. For example:
{% cache 500 project_details project.slug LANGUAGE_CODE%}
...
{% endcache %}
We invalidate this by calling:
- invalidate_template_cache("project_details", project.slug)
"""
for lang,code in settings.LANGUAGES:
cur_vars = list(variables)
cur_vars.append(unicode(lang))
args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
cache.delete(cache_key)
3
Example 7
def assertRedirectsNoFollow(self, response, expected_url, status_code=302, **querystringkwargs):
if querystringkwargs:
expected_url += '?{}'.format('&'.join('%s=%s' % (key, urlquote(value))
for (key, value) in querystringkwargs.items()))
self.assertEqual(response['Location'], '{}'.format(expected_url))
self.assertEqual(response.status_code, status_code)
3
Example 8
Project: coursys Source File: models.py
def privacy_redirect(request):
"""
Build the redirect response to give a user that needs to agree
"""
privacy_url = reverse('privacy.views.privacy')
path = '%s?%s=%s' % (privacy_url, REDIRECT_FIELD_NAME,
urlquote(request.get_full_path()))
return HttpResponseRedirect(path)
3
Example 9
Project: jellyroll Source File: lastfm.py
def _tags_for_track(artist_name, track_name):
"""
Get the top tags for a track. Also fetches tags for the artist. Only
includes tracks that break a certain threshold of usage, defined by
settings.LASTFM_TAG_USAGE_THRESHOLD (which defaults to 15).
"""
urls = [
ARTIST_TAGS_URL % (urlquote(artist_name)),
TRACK_TAGS_URL % (urlquote(artist_name), urlquote(track_name)),
]
tags = set()
for url in urls:
tags.update(_tags_for_url(url))
3
Example 10
@filter_hook
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
3
Example 11
def match_question_slug(id, slug):
slug_words = slug.split('-')
qs = Question.objects.filter(title__istartswith=slug_words[0])
for q in qs:
if slug == urlquote(slugify(q.title)):
return q
return None
3
Example 12
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 unicode key for this fragment and all vary-on's.
args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
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
Example 13
def password_required(view):
"""Decorator to force a password promt"""
def decorator(request, *args, **kwargs):
if 'password_promt' in request.session and \
isinstance(request.session['password_promt'], dict) and \
request.session['password_promt'].get('value', False):
tstart = request.session['password_promt'].get('time', 0)
pwd_age = int(time.time()) - tstart
if pwd_age < PASSWORD_PROMT_MAX_AGE:
return view(request, *args, **kwargs)
return redirect(("%s?next=%s") % (reverse("password_again"),
urlquote(request.get_full_path())))
return decorator
3
Example 14
def render(self, request, instance, **kwargs):
url = 'http://docs.google.com/viewer?url={url}&embedded=true'.format(url=urlquote(instance.url, ''))
return mark_safe(u'<iframe class="googledocsviewer" src="{src}" width="{width}" height="{height}"></iframe>'.format(
src=escape(url),
width=instance.width,
height=instance.height
))
3
Example 15
Project: SchoolIdolAPI Source File: utils.py
def singlecardurl(card):
return urlquote(u'/cards/{}/{}-{}{}{}{}-{}/'.format(
card.id,
card.rarity,
tourldash(card.name),
'-' + tourldash(card.translated_collection) if card.translated_collection else '',
'-promo' if card.is_promo else '',
'-event' if card.event_id else '',
card.attribute))
3
Example 16
Project: site Source File: smart_math.py
def inline_math(self, math):
return format_html(u'<span class="inline-math">'
ur'<img class="tex-image" src="{0}?\textstyle {2}" '
ur'''onerror="this.src=\'{1}?\textstyle {2}\';this.onerror=null" alt="{3}"/>'''
ur'<span class="tex-text" style="display:none">~{3}~</span>'
u'</span>', INLINE_MATH_SVG, INLINE_MATH_PNG, urlquote(math), math)
3
Example 17
Project: transurlvania Source File: tests.py
def testTransReverses(self):
translation.activate('en')
self.assertEqual(reverse(the_president), '/en/garfield/the-president/')
# Simulate URLResolver cache reset between requests
clear_url_caches()
translation.activate('fr')
self.assertEqual(reverse(the_president), http.urlquote(u'/fr/garfield/le-président/'))
3
Example 18
def test_doesnt_redirect_to_external_next_url(self):
next = "http://example.com"
self.client.get(self.path + '?next=' + urlquote(next))
resp = self.client.post(self.path, {
'username': self.user.username,
'password': 'admin',
'op': 'login',
})
assert resp.status_code == 302
assert next not in resp['Location']
assert resp['Location'] == 'http://testserver/auth/login/'
3
Example 19
Project: reviewboard Source File: models.py
def _make_file_cache_key(self, path, revision, base_commit_id):
"""Makes a cache key for fetched files."""
return 'file:%s:%s:%s:%s:%s' % (
self.pk,
urlquote(path),
urlquote(revision),
urlquote(base_commit_id or ''),
urlquote(self.raw_file_url or ''))
3
Example 20
Project: philo Source File: utils.py
def make_tracking_querydict(search_arg, url):
"""Returns a :class:`QueryDict` instance containing the information necessary for tracking :class:`.Click`\ s on the ``url``."""
return QueryDict("%s=%s&%s=%s&%s=%s" % (
SEARCH_ARG_GET_KEY, urlquote_plus(search_arg),
URL_REDIRECT_GET_KEY, urlquote(url),
HASH_REDIRECT_GET_KEY, make_redirect_hash(search_arg, url))
)
3
Example 21
Project: nodewatcher Source File: frontend.py
def login_url(menu_entry, context):
# If a user wants to log in we would like to take her back to the current page
# or if she has already been redirected to the current page from some other page
# then to take her back to that page. But only if the target does not require
# anonymous access which would be after logout denied.
# TODO: We might move to throwing an exception on permission denied and use 403 handler to explain that user should not be authenticated?
# TODO: Is there a way for accounts_tags.anonymous_required to work with official decorators as well?
url = urlresolvers.reverse('AccountsComponent:auth_login')
redirect_field_name = context.get('REDIRECT_FIELD_NAME', auth.REDIRECT_FIELD_NAME)
next_url = context.get('next', None) or context.get('request_get_next', None) or context['request'].GET.get(redirect_field_name, None) or context['request'].get_full_path()
if next_url and not accounts_tags.anonymous_required(next_url):
url = "%s?%s=%s" % (url, redirect_field_name, http.urlquote(next_url))
return url
3
Example 22
Project: django-radioportal Source File: standard.py
@register.filter
def secdownload_lighttpd(rel_path):
secret = getattr(settings, "RP_DL_SECRET", "verysecret")
uri_prefix = getattr(settings, "RP_DL_PREFIX", "/dl/")
hextime = "%08x" % time.time()
token = hashlib.md5((secret + rel_path + hextime).encode('utf-8')).hexdigest()
return '%s%s/%s%s' % (uri_prefix, token, hextime, urlquote(rel_path))
3
Example 23
Project: reviewboard Source File: models.py
def _make_file_exists_cache_key(self, path, revision, base_commit_id):
"""Makes a cache key for file existence checks."""
return 'file-exists:%s:%s:%s:%s:%s' % (
self.pk,
urlquote(path),
urlquote(revision),
urlquote(base_commit_id or ''),
urlquote(self.raw_file_url or ''))
3
Example 24
@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
Example 25
Project: django-forms-builder Source File: views.py
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
login_required = context["form"].login_required
if login_required and not request.user.is_authenticated():
path = urlquote(request.get_full_path())
bits = (settings.LOGIN_URL, REDIRECT_FIELD_NAME, path)
return redirect("%s?%s=%s" % bits)
return self.render_to_response(context)
3
Example 26
Project: iCQA Source File: pagination.py
def generate_uri(querydict, exclude=None):
all = []
for k, l in querydict.iterlists():
if (not exclude) or (not k in exclude):
all += ["%s=%s" % (k, urlquote(strip_tags(v))) for v in l]
return "&".join(all)
3
Example 27
Project: avos Source File: tables.py
def get_link_url(self, datum=None):
# Usable for both the container and object tables
if getattr(datum, 'container', datum):
container_name = http.urlquote(datum.name)
else:
container_name = self.table.kwargs['container_name']
subfolders = self.table.kwargs.get('subfolder_path', '')
args = (bit for bit in (container_name, subfolders) if bit)
return reverse(self.url, args=args)
3
Example 28
Project: Tangaza Source File: models.py
def send_sms_via_gateway (dest_phone, text, origin):
from django.utils.http import urlquote
logger.debug('sms_via_gateway phone %s text %s' % (dest_phone, text))
full_text = "%s\n%s" % (dest_phone, text)
encoded_text = urlquote(full_text)
content = "Channel: Local/smssend_callfile@gateway/n\n"
content += "Setvar: SMSOUT=%s\n" % (encoded_text)
content += "Extension: smssend\n"
return place_call(content)
3
Example 29
Project: django-unslashed Source File: tests.py
def test_permanent_redirect_to_unslashed_when_url_has_urlencoded_chars(self):
# urlquote is used because django.test.Client decodes the URL
# which goes against the test
slashed_url = urlquote('/testapps/quoted/foo%2Bbar%23baz%20/')
response = self.client.get(slashed_url, follow=False)
self.assertIsInstance(response, HttpResponsePermanentRedirect)
self.assertFalse(response['Location'].endswith('/'))
self.assertRegexpMatches(response['Location'], r'/quoted/foo%2Bbar%23baz%20$')
response = self.client.get(slashed_url + '?param1=1¶m2=%2Btest', follow=False)
self.assertIsInstance(response, HttpResponsePermanentRedirect)
self.assertRegexpMatches(response['Location'], r'/quoted/foo%2Bbar%23baz%20\?param1=1¶m2=%2Btest$')
3
Example 30
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
Example 31
def render(self, request, instance, **kwargs):
url = u'http://gist.github.com/{0}.js'.format(instance.gist_id)
if instance.filename:
url += u'?file={0}'.format(urlquote(instance.filename))
return mark_safe(u'<script src="{0}"></script>'.format(url))
3
Example 32
def process_request(self, request):
for exemption in self.exemptions:
if re.match(exemption, request.path):
return None
if not request.user.is_authenticated():
path = urlquote(request.get_full_path())
tup = (self.login_url, self.redirect_field_name, path)
return HttpResponseRedirect("%s?%s=%s" % tup)
3
Example 33
def redirect_if_necessary(self, current_path, product):
if self.enforce_parent and product.is_child:
return HttpResponsePermanentRedirect(
product.parent.get_absolute_url())
if self.enforce_paths:
expected_path = product.get_absolute_url()
if expected_path != urlquote(current_path):
return HttpResponsePermanentRedirect(expected_path)
3
Example 34
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)
return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())
3
Example 35
Project: django-oscar Source File: guest_checkout_tests.py
def test_redirects_new_customers_to_registration_page(self):
self.add_product_to_basket()
page = self.get(reverse('checkout:index'))
form = page.form
form['options'].select(GatewayForm.NEW)
new_user_email = '[email protected]'
form['username'].value = new_user_email
response = form.submit()
expected_url = '{register_url}?next={forward}&email={email}'.format(
register_url=reverse('customer:register'),
forward='/checkout/shipping-address/',
email=urlquote(new_user_email))
self.assertRedirects(response, expected_url)
3
Example 36
Project: transifex Source File: cache.py
def set_fragment_content(node, key_vars, context):
"""Set the rendered content of a template fragment."""
try:
for code, lang in settings.LANGUAGES:
cur_vars = list(key_vars)
cur_vars.append(unicode(code))
args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
cache_key = 'template.cache.%s.%s' % (node.fragment_name, args.hexdigest())
context['use_l10n'] = True
context['LANGUAGE_CODE'] = code
value = node.nodelist.render(context=Context(context))
cache.set(cache_key, value, settings.CACHE_MIDDLEWARE_SECONDS)
except Exception, e:
invalidate_template_cache(node.fragment_name, key_vars.keys())
3
Example 37
Project: site Source File: smart_math.py
def display_math(self, math):
return format_html(u'<span class="display-math">'
ur'<img class="tex-image" src="{0}?\displaystyle {2}" '
ur'''onerror="this.src=\'{1}?\displaystyle {2}\';this.onerror=null" alt="{3}"/>'''
ur'<span class="tex-text" style="display:none">$${3}$$</span>'
u'</span>', DISPLAY_MATH_SVG, DISPLAY_MATH_PNG, urlquote(math), math)
3
Example 38
def get_query_string(p, new_params=None, remove=None):
"""
Add and remove query parameters. From `django.contrib.admin`.
"""
if new_params is None:
new_params = {}
if remove is None:
remove = []
for r in remove:
for k in list(p):
if k == r:
del p[k]
for k, v in new_params.items():
if k in p and v is None:
del p[k]
elif v is not None:
p[k] = v
return '?' + '&'.join([u'%s=%s' % (urlquote(k), urlquote(v)) for k, v in p.items()])
3
Example 39
def build_cursor_link(self, request, name, cursor):
querystring = u'&'.join(
u'{0}={1}'.format(urlquote(k), urlquote(v))
for k, v in six.iteritems(request.GET)
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=six.text_type(cursor),
name=name,
has_results='true' if bool(cursor) else 'false',
)
3
Example 40
Project: django-adv-cache-tag Source File: tag.py
def hash_args(self):
"""
Take all the arguments passed after the fragment name and return a
hashed version which will be used in the cache key
"""
return hashlib.md5(force_bytes(':'.join([urlquote(var) for var in self.vary_on]))).hexdigest()
3
Example 41
Project: synnefo Source File: util.py
def put_container_headers(request, response, meta, policy):
if 'count' in meta:
response['X-Container-Object-Count'] = meta['count']
if 'bytes' in meta:
response['X-Container-Bytes-Used'] = meta['bytes']
response['Last-Modified'] = http_date(int(meta['modified']))
for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]:
response[urlquote(smart_str_(k))] = smart_str_(meta[k])
l = [smart_str_(x) for x in meta['object_meta']
if x.startswith('X-Object-Meta-')]
response['X-Container-Object-Meta'] = ','.join([x[14:] for x in l])
response['X-Container-Block-Size'] = request.backend.block_size
response['X-Container-Block-Hash'] = request.backend.hash_algorithm
if 'until_timestamp' in meta:
response['X-Container-Until-Timestamp'] = http_date(
int(meta['until_timestamp']))
for k, v in policy.iteritems():
response[urlquote(smart_str_(format_header_key('X-Container-Policy-' + k)))] = \
smart_str_(v)
3
Example 42
Project: django-allauth Source File: provider.py
def get_login_url(self, request, **kwargs):
method = kwargs.pop('method', self.get_method())
if method == 'js_sdk':
next = "'%s'" % escapejs(kwargs.get('next') or '')
process = "'%s'" % escapejs(
kwargs.get('process') or AuthProcess.LOGIN)
action = "'%s'" % escapejs(
kwargs.get('action') or AuthAction.AUTHENTICATE)
js = "allauth.facebook.login(%s, %s, %s)" % (next, action, process)
ret = "javascript:%s" % (urlquote(js),)
else:
assert method == 'oauth2'
ret = super(FacebookProvider, self).get_login_url(request,
**kwargs)
return ret
3
Example 43
Project: imaginationforpeople Source File: views.py
def get_answer_url(self, answer):
url = u'%(base)s%(slug)s/?answer=%(id)d#post-id-%(id)d' % {
'base': self.get_success_url(),
'slug': urlquote(slugify(answer.thread.title)),
'id': answer.id
}
return url
3
Example 44
Project: nodewatcher Source File: frontend.py
def logout_url(menu_entry, context):
# If a user wants to log out we would like to take her back to the current page
# or if she has already been redirected to the current page from some other page
# then to take her back to that page. But only if the target does not require
# authenticated access which would be after logout denied.
# TODO: We should probably check not just if url requires authenticated access, but if user has permissions for access
# TODO: We might move to throwing an exception on permission denied and show an login form inside 403 handler?
# TODO: Is there a way for accounts_tags.authenticated_required to work with official decorators as well?
url = urlresolvers.reverse('AccountsComponent:auth_logout')
redirect_field_name = context.get('REDIRECT_FIELD_NAME', auth.REDIRECT_FIELD_NAME)
next_url = context.get('next', None) or context.get('request_get_next', None) or context['request'].GET.get(redirect_field_name, None) or context['request'].get_full_path()
if next_url and not accounts_tags.authenticated_required(next_url):
url = "%s?%s=%s" % (url, redirect_field_name, http.urlquote(next_url))
return url
3
Example 45
Project: django-cache-sweeper Source File: utils.py
def generate_fragment_cache_key_for_record(record, *cache_keys):
unique_fragment_key = u":".join(map(lambda key: urlquote(str(key)), cache_keys))
unique_fragment_key_hash = md5_constructor(unique_fragment_key)
record_version_key = cache_token_key_for_record(record)
record_current_version = cache.get(record_version_key, None)
# cache miss for a record that hasn't been versioned yet or
# has been expired by memcached
if record_current_version == None:
cache.set(record_version_key, 0, 0)
record_current_version = 0
cache_key = 'cachesweeper.%s.%s.%s' % (
record_version_key,
record_current_version,
unique_fragment_key_hash.hexdigest()
)
return cache_key
3
Example 46
def __call__(self, request, *args, **kwargs):
if self.test_func(request.user):
return self.view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = self.login_url, self.redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
3
Example 47
Project: django-mediagenerator Source File: utils.py
def refresh_dev_names():
global _generated_names, _backend_mapping
generated_names = {}
backend_mapping = {}
for backend in _load_generators():
for key, url, hash in backend.get_dev_output_names():
versioned_url = urlquote(url)
if hash:
versioned_url += '?version=' + hash
generated_names.setdefault(key, [])
generated_names[key].append(versioned_url)
backend_mapping[url] = backend
with _refresh_dev_names_lock:
_generated_names, _backend_mapping = generated_names, backend_mapping
3
Example 48
Project: classic.rhizome.org Source File: decorators.py
def user_passes_membership_test(test_func, membershp_url="/membership_required/", redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
return HttpResponseRedirect('%s' % membershp_url)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
3
Example 49
Project: djangotribune Source File: archives.py
def get_search_url_args(self):
"""
Return the search's URL args to use in pagination URLs
"""
if len(self.search_filters)>0:
filter_args = ["{k}={v}".format(k=k,v=urlquote(v)) for k,v in self.search_filters]
return self.url_search_start_arg+"&".join(filter_args)
return ''
3
Example 50
def get_full_url(self):
"""Returns the encoded absolute URL path with its query string.
This is used for the POST action attribute on the form element
wrapping the table. We use this method to persist the
pagination marker.
"""
url = super(ObjectsTable, self).get_full_url()
return http.urlquote(url)