My project requires different request payload for different endpoints. I am generating each one of them in python code and pass the generated payload to the python requests library. It's working but I am looking for a more elegant/cleaner way to do it. I was thinking about having yaml files and read them to generate my payload. Looking for more ideas and better way to generate request payload.
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)
It doesn't matter if you use YAML or JSON. Look at this code:
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)
this will generate 4 calls like this:
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'}
and if you want to use put them in a yaml or json file and load it in the request_map
variable. You don't need do any other operation on them. like:
request_map = yaml.safe_load(open('request_map.yaml'))
or:
request_map = json.load(open('request_map.json'))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments