2

Is there a way to use the python Requests module to urlencode a string without sending an actual request?

This can be done with urllib as seen here:

>>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

I couldn't find any Requests documentation that shows how to achieve a comparable result.

Thanks in advance,

Wilhelm

Wilhelm Klopp
  • 5,030
  • 2
  • 29
  • 37

2 Answers2

7

Requests uses the standard library for these functions, and makes them available through its compat module:

>>> import requests.compat
>>> requests.compat.quote_plus
<function quote_plus at 0x10eb12de8>
>>> requests.compat.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'

This module also insulates your code from Python 2/3 issues.

(as @LittleQ points out, it's also exported through the utils module as follows:

from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
                     builtin_str, getproxies, proxy_bypass, urlunparse,
                     basestring)

...and that's probably a more obvious way to call that functionality.

bgporter
  • 35,114
  • 8
  • 59
  • 65
3

In both python2 and python3:

import requests

quoted = requests.utils.quote('string_of_characters_like_these:$#@=?%^Q^$')

The quoted string would be:

'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'
LittleQ
  • 1,860
  • 1
  • 12
  • 14