Python请求-动态传递HTTP动词 [英] Python Requests - Dynamically Pass HTTP Verb
问题描述
是否有一种方法可以将HTTP动词(PATCH/POST)传递给函数,并动态地将该动词用于Python请求?
Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?
例如,我希望此函数采用一个动词"变量,该变量只能在内部调用,并且可以是= post/patch.
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]}
谢谢大家!
推荐答案
对于请求库, requests.request
方法(如Guillaume的答案所示).
With the request library, the requests.request
method can be relied on directly (as Guillaume's answer suggested).
但是,当遇到不具有通用方法的库(具有相似的调用签名的方法)时,可以为getattr
提供所需方法的名称,并将其作为具有默认值的字符串.也许像
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
对于默认值,它可以是一个适当的操作,或者只是将其省略而将引发异常;由您决定如何处理.我将其保留为None
,因此您可以在else
部分中处理其他情况.
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.
这篇关于Python请求-动态传递HTTP动词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!