Hec*_*407 6 python http request http-verbs
有没有办法将HTTP动词(PATCH/POST)传递给函数并动态地将该动词用于Python请求?
例如,我希望这个函数采用一个'动词'变量,该变量只在内部调用,或者= 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)
Run Code Online (Sandbox Code Playgroud)
我意识到我不能请求.如上所述''''',它的意思是说明问题.有没有办法做到这一点或类似的东西?我想避免:
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]}
Run Code Online (Sandbox Code Playgroud)
多谢你们!
Gui*_*ume 20
只需使用该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]}
)
Run Code Online (Sandbox Code Playgroud)
使用请求库,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
Run Code Online (Sandbox Code Playgroud)
对于默认值,它可以是一个适当的操作,也可以不做任何设置,否则将引发异常。由您决定如何处理。我将其保留为原样,None
以便您可以在本else
节中处理替代情况。
归档时间: |
|
查看次数: |
7546 次 |
最近记录: |