CreatingAndWorkingWithURLs

From XPUB & Lens-Based wiki

Creating and working with URLs

The urllib library provides many useful functions for creating URLs (useful to generate a CGI link for instance), or unparsing an existing link into it's parts.

Mapping a python dictionary to a URL query

urllib.urlencode(query doseq)

imgsrc = "thumb.cgi?"+urllib.urlencode({'f': filepath, 't': 5})
print """<img src="%s" />""" % imgsrc


quote(string safe)

Replace special characters in string using the "%xx" escape. Letters, digits, and the characters "_.-" are never quoted. The optional safe parameter specifies additional characters that should not be quoted -- its default value is '/'.

quote('/~connolly/') yields '/%7econnolly/'.


quote_plus(string safe)

Like quote(), but also replaces spaces by plus signs, as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.

unquote(string)

Replace "%xx" escapes by their single-character equivalent.

unquote('/%7Econnolly/') yields '/~connolly/'.


unquote_plus(string)

Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values.

keep in mind

  • To make sure slashes get quoted, you need to override the default "safe" value, as in:
nexturl = "goto.cgi?path=%s" % urllib.quote(mypath, '')


source: http://docs.python.org/lib/module-urllib.html