How to urlencode a querystring in Python?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 How To Urlencode A Querystring In Python?
00:11 Accepted Answer Score 735
00:45 Answer 2 Score 1321
01:12 Answer 3 Score 37
01:25 Answer 4 Score 100
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/5607...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #urllib #urlencode
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 How To Urlencode A Querystring In Python?
00:11 Accepted Answer Score 735
00:45 Answer 2 Score 1321
01:12 Answer 3 Score 37
01:25 Answer 4 Score 100
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/5607...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #urllib #urlencode
#avk47
ANSWER 1
Score 1321
Python 2
What you're looking for is urllib.quote_plus:
safe_string = urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
#Value: 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'
Python 3
In Python 3, the urllib package has been broken into smaller components. You'll use urllib.parse.quote_plus (note the parse child module)
import urllib.parse
safe_string = urllib.parse.quote_plus(...)
ACCEPTED ANSWER
Score 735
You need to pass your parameters into urlencode() as either a mapping (dict), or a sequence of 2-tuples, like:
>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'
Python 3 or above
>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event
Note that this does not do url encoding in the commonly used sense (look at the output). For that use urllib.parse.quote_plus.
ANSWER 3
Score 100
Try requests instead of urllib and you don't need to bother with urlencode!
import requests
requests.get('http://youraddress.com', params=evt.fields)
EDIT:
If you need ordered name-value pairs or multiple values for a name then set params like so:
params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
instead of using a dictionary.