我有一个APIClient类的方法。而且我需要优化if-else语句以处理所有HTTP方法,而不使用条件层次结构。我该怎么做?我曾尝试使用字典,但似乎做起来不正确
def make_request(self, method: str, request_url: str, data: dict=None, headers=None):
url = self._build_url(request_url)
try:
if method == 'POST':
resp = requests.post(url, data=data, headers=headers, verify=False)
elif method == 'GET':
resp = requests.get(url, headers=headers, verify=False)
return resp
except requests.exceptions.RequestException:
raise APINotRespondingeError()
答案 0 :(得分:1)
我使用了getattr()方法。请注意,方法参数应为小写
def make_request(self, method: str, request_url: str, data: dict=None):
url = self._build_url(request_url)
try:
get_response = getattr(requests, method, None)
response = get_response(url, data=data, headers=self.headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as err:
status_code = None if err.response is None else err.response.status_code
raise APIResponseError(error=err)