absurd
absurd

Reputation: 1115

python3 requests use quote instead of quote_plus

I use Python 3 and the requests module/library for querying a REST service.

It seems that requests by default uses urllib.parse.quote_plus() for urlencoding, i.e. spaces are converted to +.

However the REST service I query misinterpretes this as and. So I need to encode spaces as %20, i.e. use urllib.parse.quote() instead.

Is there an easy way to do this with requests? I couldn't find any option in the documentation.

Upvotes: 21

Views: 40200

Answers (2)

RandyMcMillan
RandyMcMillan

Reputation: 55

for context...

add an alias to your .aliases file:

alias urlencode='$(which python3) -c "import sys; from requests.utils import requote_uri; print(requote_uri(sys.argv[1]));"'

then:

source .aliases && urlencode "https://www.somerandom.com/?name=Something Cool"

screenshot

Upvotes: 0

gallen
gallen

Reputation: 1292

It turns out you can!

from requests.utils import requote_uri
url = "https://www.somerandom.com/?name=Something Cool"
requote_uri(url)

'https://www.somerandom.com/?name=Something%20Cool'

documentation here The requote_uri method is about halfway down the page.

Upvotes: 33

Related Questions