我有两个函数,它们采用相同的 header 。我可以在全局保存这样我就不需要每次都打电话
def funct1():
json_d = {"group_id": "uid"}
headers = {"account-id":"xxx","api-key":"xxx","Content-Type": "application/json"}
response = requests.post("https://example.com/docs",headers=headers,json=json_d)
def funct2():
json_d = {"group_id": "uid"}
headers = {"account-id":"xxx","api-key":"xxx","Content-Type": "application/json"}
response = requests.post("https://example.com/docs",headers=headers,json=json_d)
我可以吗
headers = {"account-id":"xxx","api-key":"xxx","Content-Type": "application/json"}
全局 header
最佳答案
我建议为默认 http 调用创建一个函数。
在这种情况下,每个函数只有 json_d 不同。也许这也将是 URL 或其他东西,您可以轻松地将它们向上移动到初始函数,并在 default_post()
函数中对它们进行参数化。
使用**kwargs
,您可以使其更加通用,例如,如果您想传递超时,您可以调用default_post(..., timeout=3)
它会自动传递给 requests.post
函数。
示例
def funct1():
json_d_1 = {
"group_id": "uid_1"
}
default_post(json_d_1)
def funct2():
json_d_2 = {
"group_id": "uid_2"
}
default_post(json_d_2)
def default_post(json_d, ..., **kwargs):
headers = {"account-id":"xxx","api-key":"xxx","Content-Type": "application/json"}
response = requests.post(
"https://example.com/docs",
headers=headers,
json=json_d,
**kwargs
)
return response
关于python - 如何在全局保存 header api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451509/