Reputation: 1115
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
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"
Upvotes: 0
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