gpt4 book ai didi

Python 请求 - 动态传递 HTTP 动词

转载 作者:太空狗 更新时间:2023-10-29 22:01:52 25 4
gpt4 key购买 nike

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

谢谢大家!

最佳答案

只需使用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]}
)

关于Python 请求 - 动态传递 HTTP 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com