在 python 代码中为不同端点生成多个负载的最佳约定是什么?

What is the best convention to generate multiple payload for different endpoints in python code?

我的项目需要针对不同端点的不同请求负载。我在 python 代码中生成它们中的每一个,并将生成的有效负载传递给 python 请求库。它正在工作,但我正在寻找一种更 elegant/cleaner 的方法来做到这一点。我正在考虑拥有 yaml 文件并读取它们以生成我的有效负载。寻找更多想法和更好的方法来生成请求负载。

def abc(self):
    payload = {
             'key1' :'1',
             'key2' : '2'
               }
     return payload

def call_abc(self):
    request_payload = self.abc()
    requests.post(url, json=request_payload, headers)

使用 YAML 还是 JSON 都没有关系。看这段代码:

request_map = {
    "http://some/end/point": [
        {
            'key1': '1',
            'key2': '2'
        },
        {
            'key3': '4',
            'key4': '5'
        }
    ],
    "http://some/other/end/point": [
        {
            'key1': '1',
            'key2': '2'
        },
        {
            'key3': '4',
            'key4': '5'
        }
    ]
}

def generate_call():
    for endpoint, payloads in request_map.items():
        for payload in payloads:
            yield endpoint, payload


def call_endpoint(url, payload):
    requests.post(url, data=payload)


if __name__ == "__main__":
    for url, payload in generate_call():
        call_endpoint(url, payload)  

这将生成 4 个这样的调用:

http://some/end/point {'key1': '1', 'key2': '2'}
http://some/end/point {'key3': '4', 'key4': '5'}
http://some/other/end/point {'key1': '1', 'key2': '2'}
http://some/other/end/point {'key3': '4', 'key4': '5'}

如果您想使用它们,请将它们放入 yaml 或 json 文件中,然后将其加载到 request_map 变量中。您不需要对它们进行任何其他操作。 喜欢:

request_map = yaml.safe_load(open('request_map.yaml'))

或:

request_map = json.load(open('request_map.json'))