Python 请求 - 动态传递 HTTP 动词

Python Requests - Dynamically Pass HTTP Verb

有没有办法将 HTTP 谓词 (PATCH/POST) 传递给函数并动态地使用该谓词进行 Python 请求?

例如,我希望此函数接受一个仅在内部调用的 'verb' 变量,并且将 = 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)

我知道我不能请求。'verb' 如上所述,这是为了说明问题。有没有办法做到这一点或类似的事情?我想避免:

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

谢谢大家!

有了request库,就可以直接依赖requests.request方法了(正如Guillaume的回答所建议的那样)。

但是,当遇到没有针对具有相似调用签名的方法的通用方法的库时,getattr 可以提供所需方法的名称作为具有默认值的字符串。可能喜欢

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

对于默认值,它可以是一个适当的动作,或者只是离开它会引发异常;这取决于你想如何处理它。我将其保留为 None,因此您可以在 else 部分处理其他情况。

只需使用request()方法。第一个参数是您要使用的 HTTP 动词。 get()post()等只是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]}
)