Re: urldecode function?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fredrik Lundh

    Re: urldecode function?

    rkmr.em@gmail.c om wrote:
    is there a function that does the opposite of urllib.urlencod e?
    >
    for example
    urldecode('Cat= 1&by=down&start =1827')
    >
    returns a dictionary with {'Cat':1, 'by':'down','st art':1827)
    the cgi modules contains assorted stuff for parsing serialized HTTP
    forms and query strings. here's a quick way to get a dictionary:
    >>import cgi
    >>dict(cgi.pars e_qsl("Cat=1&by =down&start=182 7"))
    {'start': '1827', 'by': 'down', 'Cat': '1'}

    there's also:
    >>cgi.parse_qs( "Cat=1&by=down& start=1827")
    {'start': ['1827'], 'by': ['down'], 'Cat': ['1']}
    >>cgi.parse_qsl ("Cat=1&by=down &start=1827" )
    [('Cat', '1'), ('by', 'down'), ('start', '1827')]

    (both these forms handle multiple instances of the same key)

    to autoconvert things that look like integers, you can do e.g.
    >>def safeint(x):
    .... try:
    .... return int(x)
    .... except ValueError:
    .... return x # leave as is
    ....
    >>dict((k, safeint(v)) for k, v in
    cgi.parse_qsl(" Cat=1&by=down&s tart=1827"))
    {'start': 1827, 'by': 'down', 'Cat': 1}

    </F>

Working...