urlquote() and urlencode() in one method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from django.utils.http import urlquote  as django_urlquote
from django.utils.http import urlencode as django_urlencode
from django.utils.datastructures import MultiValueDict

def urlquote(link=None, get={}):
    u'''
    This method does both: urlquote() and urlencode()

    urlqoute(): Quote special characters in 'link'

    urlencode(): Map dictionary to query string key=value&...

    HTML escaping is not done.

    Example:

      urlquote('/wiki/Python_(programming_language)')     --> '/wiki/Python_%28programming_language%29'
      urlquote('/mypath/', {'key': 'value'})              --> '/mypath/?key=value'
      urlquote('/mypath/', {'key': ['value1', 'value2']}) --> '/mypath/?key=value1&key=value2'
      urlquote({'key': ['value1', 'value2']})             --> 'key=value1&key=value2'
    '''
    assert link or get
    if isinstance(link, dict):
        # urlqoute({'key': 'value', 'key2': 'value2'}) --> key=value&key2=value2
        assert not get, get
        get=link
        link=''
    assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
    assert not (link.startswith('http://') or link.startswith('https://')), \
        'This method should only quote the url path. It should not start with http(s)://  (%s)' % (
        link)
    if get:
        # http://code.djangoproject.com/ticket/9089
        if isinstance(get, MultiValueDict):
            get=get.lists()
        if link:
            link='%s?' % django_urlquote(link)
        return u'%s%s' % (link, django_urlencode(get, doseq=True))
    else:
        return django_urlquote(link)

More like this

  1. Wizard class by king 6 years, 11 months ago
  2. Add httponly to session cookie by rodolfo.3 4 years ago
  3. lazy url reverse() by guettli 6 years, 4 months ago
  4. Add ValidationError to a field instead of __all__ during Form.clean() by guettli 5 years, 6 months ago
  5. More admin clock time increments by robharvey 7 years ago

Comments

(Forgotten your password?)