Python Requests - Dynamically Pass HTTP Verb

戏子无情 提交于 2020-08-24 05:50:07

问题


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!


回答1:


With the request library, the requests.request method can be relied on directly (as Guillaume's answer suggested).

However, when encountering against libraries that don't have a generic method for methods that have similar calling signatures, getattr can be supplied with the name of the desired method as a string with a default value. Maybe like

action = getattr(requests, verb, None)
if action:
    action(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
else:
    # handle invalid action as the default value was returned

For the default value it can be a proper action, or just leave it out and an exception will be raised; it's up to you how you want to handle it. I left it as None so you can deal with alternative case in the else section.




回答2:


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]}
)


来源:https://stackoverflow.com/questions/39324970/python-requests-dynamically-pass-http-verb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!