Python URLencoding特定结果

问题描述 投票:0回答:1

我正在使用Python 3.8.2在数据库中进行查询

我需要使用Urlencoded结果:

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:\Users\Johnathan\Desktop\Python Snippets\test_func.py", line 17, in <module>
    print(urllib.parse.quote_plus(data))
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 855, in quote_plus
    string = quote(string, safe + space, encoding, errors)
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 839, in quote
    return quote_from_bytes(string, safe)
  File "C:\Users\Johnathan\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 864, in quote_from_bytes
    raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes

我尝试了几种其他方法,并收到:?where =%7B%27date%27%3A +%2703%2F30%2F20%27%7D

长话短说,我需要对以下内容进行网址编码


data = {"where":{"date":"03/30/20"}}

needed_encoded_data = ?where=%7B%22date%22%3A%20%2203%2F30%2F20%22%7D

谢谢

python python-3.x curl python-requests urlencode
1个回答
0
投票

where是字典-不能进行网址编码。您需要先将其转换为字符串或字节对象。

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.