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



我的项目需要针对不同端点的不同请求有效负载。我在 python 代码中生成它们中的每一个,并将生成的有效负载传递给 python 请求库。它正在工作,但我正在寻找一种更优雅/更清洁的方式来做到这一点。我正在考虑拥有 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'))

相关内容

最新更新