Python请求-动态传递HTTP动词

2024-04-23 13:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以将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)

我意识到我不能要求“动词”,就像我上面说的,它是用来说明这个问题的。有办法这样做吗?我想避免:

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

谢谢你们!


Tags: selfauthapijsonurldns动词record
2条回答

使用请求库,可以直接依赖^{}方法(正如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]}
)

相关问题 更多 >