Python 请求 urlencode 而不发送任何请求

Python requests urlencode without sending any request

有没有办法在不发送实际请求的情况下使用 python 请求模块对字符串进行 urlencode?

这可以用 urllib 来完成 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'

我找不到任何说明如何获得可比结果的 Requests 文档。

提前致谢,

威廉

Requests 使用标准库来实现这些功能,并通过其 compat 模块提供它们:

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

此模块还将您的代码与 Python 2/3 问题隔离开来。

(正如@LittleQ 指出的,它也是通过 utils 模块导出的,如下所示:

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

...这可能是调用该功能的更明显的方式。

在 python2 和 python3 中:

import requests

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

引用的字符串将是:

'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24'