Python Requests - Dynamically Pass HTTP Verb

HectorOfTroy407 picture HectorOfTroy407 · Sep 5, 2016 · Viewed 15.5k times · Source

Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?

For example, I want this function to take a 'verb' variable which is only called internally and will either = post/patch.

def dnsChange(self, zID, verb):
    for record in config.NEW_DNS:
        ### LINE BELOW IS ALL THAT MATTERS TO THIS QUESTION 
        json = requests.verb(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
        key = record[0] + "record with host " + record[1]
        result = json.loads(json.text)
        self.apiSuccess(result,key,value)

I realize I cannot requests.'verb' as I have above, it's meant to illustrate the question. Is there a way to do this or something similar? I'd like to avoid an:

if verb == 'post':
    json = requests.post(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
else:
    json = requests.patch(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}

Thanks guys!

Answer

Guillaume picture Guillaume · Sep 5, 2016

Just use the request() method. First argument is the HTTP verb that you want to use. get(), post(), etc. are just aliases to request('GET'), request('POST'): https://requests.readthedocs.io/en/master/api/#requests.request

verb = 'POST'
response = requests.request(verb, headers=self.auth,
     url=self.API + '/zones/' + str(zID) + '/dns_records',
     data={"type":record[0], "name":record[1], "content":record[2]}
)