python - 如何在全局保存 header api

标签 python

我有两个函数,它们采用相同的 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/

相关文章:

python - matlab find() 在 python 中查找非零元素

python - Pandas TimeGrouper 问题 - "time"索引上的类型错误

python - 使用 openpyxl 编辑 Excel 文件时丢失合并单元格边框

python - numpy 二维和一维加法平面

python - 使用 Scipy minimize 进行 Keras BFGS 训练

Python numba.jit 类型

python - 使用 Python 中的函数比较时间戳(使用 Delorean)

python - 当有平局时, Pandas 如何决定排序?

android - 在 jython 中编写 Android 应用程序

python - 仅 2 个元素的快速排序