我试图了解从这个doc蟒蛇装饰。并正在编写我自己的装饰器来处理API异常。访问参数
但是在我的装饰器中,我没有得到如何在自定义装饰器中访问参数(method
,api
和data
)。
我知道,我没有通过任何地方method
因为我没有得到该到哪里,这样我可以在我的装饰接受它。
这里是我的装饰:
import requests as r
import json
def handle_api_exceptions(http_api_call):
""" """
def wrapper(*args, **kwargs):
""" """
response = {}
try:
response = http_api_call(*args, **kwargs)
if response.ok:
result = response.json()
if result.get('code', 200) in INVALID_STATUS_CODES: #INVALID_STATUS_CODES = [1801, 1803, 1806,... ]
response = {"data":{}, "status":False}
else:
return result
else:
capture_failed_requests(method, api, data, response,
error=None, reason=response.reason)
return {}
except r.exceptions.ConnectionError as e:
capture_failed_requests(method, api, data, response, error=e,
reason="Connection Aborted")
return {}
except json.decoder.JSONDecodeError as e:
capture_failed_requests(method, api, data, response, error=e,
reason="Invalid Response")
return {}
except r.exceptions.ReadTimeout as e:
capture_failed_requests(method, api, data, response, error=e,
reason="Request Timed Out")
return {}
except Exception as e:
capture_failed_requests(method, api, data, response, error=e,
reason="Internal Server Error")
return {}
return wrapper
定制GET,POST API请求:
@handle_api_exceptions
def get(self, api, data, token=None):
""" """
if token:data.update(self.get_token(token))
response = r.get(api, data, verify=self.config.SSL_VERIFY,
timeout=self.config.REQUEST_TIMEOUT)
return response
@handle_api_exceptions
def post(self, api, data, token=None):
""" """
if token:
data.update(self.get_secret_token(token))
response = r.post(api, data, verify=self.config.SSL_VERIFY,
timeout=self.config.REQUEST_TIMEOUT)
return response
def post_call(self):
""" """
api = "http://192.168.0.24/api/v1/reset/"
data = {"k1":[], "k2":{}, "id":123456} #-- Some Key val
return self.post(api, data, token="SOME_SECRET_TOKEN")
查询是:如何通过method
,api
和data
在capture_failed_requests()
?
你不可错过'method'按照目前编写的,但'data'和'api'只是在'args'。 – jonrsharpe
@jonrsharpe:我可以从某处传递硬编码方法=“GET”或method =“POST”吗? – Laxmikant
是的,你可以传递给装饰直接:'@handle_api_exceptions(方法= 'GET')'。请记住:http://stackoverflow.com/q/5929107/3001761 – jonrsharpe