Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to urlencode a querystring in Python?

I am trying to urlencode this string before I submit.

queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];  
like image 712
James Avatar asked Apr 09 '11 20:04

James


People also ask

Does Python requests URL encode?

In Python, we can URL encode a query string using the urlib. parse module, which further contains a function urlencode() for encoding the query string in URL.

What does Urllib parse URL encode do?

parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.


2 Answers

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(...) 
like image 80
Ricky Sahu Avatar answered Sep 18 '22 23:09

Ricky Sahu


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

Use:

>>> 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.

like image 37
bgporter Avatar answered Sep 21 '22 23:09

bgporter