If I do
url = "http://example.com?p=" + urllib.quote(query)
- It doesn't encode
/
to%2F
(breaks OAuth normalization) - It doesn't handle Unicode (it throws an exception)
Is there a better library?
If I do
url = "http://example.com?p=" + urllib.quote(query)
/
to %2F
(breaks OAuth normalization)Is there a better library?
My answer is similar to Paolo's answer.
I think module
requests
is much better. It's based onurllib3
. You can try this:It is better to use
urlencode
here. Not much difference for single parameter but IMHO makes the code clearer. (It looks confusing to see a functionquote_plus
! especially those coming from other languates)Docs
urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode
quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus
In Python 3,
urllib.quote
has been moved tourllib.parse.quote
and it does handle unicode by default.From the docs:
That means passing '' for safe will solve your first issue:
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
By the way have a look at urlencode
Note that
urllib.quote
moved tourllib.parse.quote
in Python3If you're using django, you can use urlquote:
Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http: