需求:将字典类型的URL参数,进行URL编码
将
{"query_hash":"69cba40317214236af40e7efa697781d","variables":{"id":"15756602186","first":12}}
转化为:
query_hash=69cba40317214236af40e7efa697781d&variables=%7B%22id%22%3A%2215756602186%22%2C%22first%22%3A12%7D
如果直接调用urlencode编码出来的URL参数,和浏览器看到的不一样,多了+号
from urllib.parse import urlencode
params ={"query_hash":"69cba40317214236af40e7efa697781d","variables":{"id":"15756602186","first":12}}
print(urlencode(params))
输出 query_hash=69cba40317214236af40e7efa697781d&variables=%7B%27id%27%3A+%2715756602186%27%2C+%27first%27%3A+12%7D
问了一圈有大佬说这是urllib.parse的bug
urlencode编码嵌套的字典就会出现这样的问题
转了一圈,解决方案有两种:
- 方案一、
params = quote(json.dumps({"id":"15756602186","first":12},separators=(',', ':')))
payload = f'query_hash=69cba40317214236af40e7efa697781d&variables={params}'
print(payload)
- 方案二、
params = {"query_hash":"69cba40317214236af40e7efa697781d","variables":'{"id":"15756602186","first":12}'}
print(urlencode(params))
这种方案有个风险,比如通过传参的方式传入variables,就无法成功编码
dynamic_params = {"id":"15756602186","first":50}
params = {"query_hash": "69cba40317214236af40e7efa697781d", "variables": f'{dynamic_params}'}
print(params)
网友评论