如何将查询字符串传递给request.get的参数?

时间:2019-03-23 22:57:42

标签: python

给出的是一个字符串:

'search=hello+world&status=something&cache=false' 

如果不确定我将始终从字符串中获取哪些参数以便在requests.get()中使用它,那么如何将参数和值从该字符串传递至有效负载字典?

requests.get(url, params=payload, headers=headers)

3 个答案:

答案 0 :(得分:1)

您可以给出以下内容

url = url + '?'+ your_parm_string
r = requests.get(url, headers=headers)

答案 1 :(得分:1)

string = 'search=hello+world&status=something&cache=false'
params = string.split('&')
payload = {}
for params in param:
    p = param.split('=')
    payload[p[0]] = p[1]
print(payload)
{'search': 'hello+world', 'status': 'something', 'cache': 'false'}

答案 2 :(得分:1)

使用def split_params(param_string): return {param: value for param, value in (pair.split('=') for pair in param_string.split('&'))} split_params('search=hello+world&status=something&cache=false') 理解

{'search': 'hello+world', 'status': 'something', 'cache': 'false'}

输出:

&

这是基于以下观察:每个参数值对在外部由=隔开,在内部由class User(models.Model): name = models.CharField(max_length=30, primary_key=True, blank=False) # etc... class ToDo(models.Model): title = models.CharField(max_length=50, primary_key=True, blank=False) description = models.TextField(blank=True, null=True) user = models.ForeignKey(User, blank=True on_delete=models.CASCADE) 隔开。