47

Why am I getting this error when trying to urlencode this string

 >>> callback = "http://localhost/application/authtwitter?twitterCallback"
 >>> urllib.urlencode(callback)
 Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.7/urllib.py", line 1261, in urlencode
      raise TypeError
 TypeError: not a valid non-string sequence or mapping object
DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
BillPull
  • 6,853
  • 15
  • 60
  • 99

4 Answers4

63

That's not what that function does:

urlencode(query, doseq=0)
    Encode a sequence of two-element tuples or dictionary into a URL query string.

Are you looking for?

  • urllib.quote(callback) Python 2
  • urllib.parse.quote(callback) Python 3
fusion27
  • 2,396
  • 1
  • 25
  • 25
retracile
  • 12,167
  • 4
  • 35
  • 42
  • 2
    This answer only works for Python 2. For Python 3, it is urllib.parse.quote. Can you add an addendum? – kloddant Dec 23 '19 at 15:11
19

Python is not PHP. You want urllib.quote() instead.

maazza
  • 7,016
  • 15
  • 63
  • 96
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
13

urlencode()

This function encode two-element tuples or dictionary only.

  >>> import urllib  
  >>> dict = { 'First_Name' : 'Jack', 'Second_Name' : "West"}
  >>> urllib.urlencode(dict)
  'First_Name=Jack&Second_Name=West

quote_plus()

This function encode url string

  >>> import urllib   
  >>> url ="https://www.google.com/"
  >>> urllib.quote_plus(url)
  'https%3A%2F%2Fwww.google.com%2F'
Vicky
  • 5,098
  • 2
  • 33
  • 31
11

Python 3

In Python 3, the quote and urlencode functionalities are located in the module urllib.parse.

Some Examples:

(un)quote

urllib.parse.quote

Replace special characters in string using the %xx escape.

>>> import urllib.parse
>>> urllib.parse.quote('https://www.google.com/')
'https%3A//www.google.com/'

Similarly, to reverse this operation, use urllib.parse.unquote:

urllib.parse.unquote

Replace %xx escapes by their single-character equivalent.

>>> import urllib.parse
>>> urllib.parse.unquote('https%3A//www.google.com/')
'https://www.google.com/'

(un)quote_plus

urllib.parse.quote_plus

Like quote(), but also replace spaces by plus signs, as required for quoting HTML form values when building up a query string to go into a URL.

>>> import urllib.parse
>>> urllib.parse.quote_plus('https://www.google.com/')
'https%3A%2F%2Fwww.google.com%2F'

Similarly, to reverse this operation, use urllib.parse.unquote_plus:

urllib.parse.unquote_plus

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

>>> import urllib.parse
>>> urllib.parse.unquote_plus('https%3A%2F%2Fwww.google.com%2F')
'https://www.google.com/'

urlencode

urllib.parse.urlencode

>>> import urllib.parse
>>> d = {'url': 'https://google.com', 'event': 'someEvent'}
>>> urrlib.parse.urlencode(d)
'url=https%3A%2F%2Fgoogle.com&event=someEvent'
ncw
  • 1,635
  • 1
  • 18
  • 26