我正在从Python 3.8.2 中的数据库进行查询
我需要url编码的结果是:
data = {"where":{"date":"03/30/20"}}
needed_results = ?where=%7B%22date%22%3A%20%2203%2F30%2F20%22%7D
我试过以下
import urllib.parse
data = {"where":{"date":"03/30/20"}}
print(urllib.parse.quote_plus(data))
当我这样做时,我会得到以下
Traceback (most recent call last):
File "C:UsersJohnathanDesktopPython Snippetstest_func.py", line 17, in <module>
print(urllib.parse.quote_plus(data))
File "C:UsersJohnathanAppDataLocalProgramsPythonPython38-32liburllibparse.py", line 855, in quote_plus
string = quote(string, safe + space, encoding, errors)
File "C:UsersJohnathanAppDataLocalProgramsPythonPython38-32liburllibparse.py", line 839, in quote
return quote_from_bytes(string, safe)
File "C:UsersJohnathanAppDataLocalProgramsPythonPython38-32liburllibparse.py", line 864, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
我尝试了其他几种方法,收到了:?其中=%7B%27date%27%3A+%2703%2F30%2F20%27%7D
长话短说,我需要url编码以下
data = {"where":{"date":"03/30/20"}}
needed_encoded_data = ?where=%7B%22date%22%3A%20%2203%2F30%2F20%22%7D
感谢
where
是一个字典,不能对其进行url编码。您需要先将其转换为字符串或字节对象。
你可以用json.dumps
做到这一点
import json
import urllib.parse
data = {"where":{"date":"03/30/20"}}
print(urllib.parse.quote_plus(json.dumps(data)))
输出:
%7B%22where%22%3A+%7B%22date%22%3A+%2203%2F30%2F20%22%7D%7D