【问题标题】:How to handle HTTP Status Codes across a Python application?如何在 Python 应用程序中处理 HTTP 状态码?
【发布时间】:2018-01-18 16:30:07
【问题描述】:

我正在尝试标准化我对从各种 API 返回的 HTTP 状态代码的处理,以减少我跨文件复制的代码量。

对于我当前的应用程序,我有一组文件,每个文件都包含一个类,这些类都从一个主类继承。我正在使用 Python 请求模块来使用 API。

到目前为止,我已经在每个函数中编写了自定义状态代码处理以继续使用 200,使用 400 记录我发送的请求,记录 404 的 url,重试 5xx,但是继续复制很麻烦此代码跨函数和类。

我正在考虑以下问题(请注意,我已将代码简化为仅使用 GET,但实际上,我主要是在发布和接收 json 响应):

apiMaster.py

class ApiMaster(object):
    def _handle_response(self, resp):
        if resp.status_code == 200: # or requests.code.ok
            return resp.json()
        if resp.status_code == 400:
            err_msg = "400 Error - Bad Request\n" + resp.request.url + "\n" + resp.request.data
            raise HTTPError(err_msg)
        ...

apiA.py

class Api_A(ApiMaster):
    def query_json_a(self):
        resp = requests.get(self.url + '/a.json')
        try:
            resp_json = self._handle_response(resp)
        except HTTPError as e:
            logger.error(str(e))

apiB.py

class Api_B(ApiMaster):
    def query_json_b(self):
        # same as API A but with different endpoints and purpose

但是,这似乎仍然存在问题。我不知道尝试考虑 API 返回的每个状态代码是否合理。这还需要我将此代码复制到我开始从事的任何新项目中。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python http error-handling python-requests http-error


    【解决方案1】:

    您的解决方案似乎不错,您可以通过将更多内容移动到共享方法中来进一步完善它,例如

    class ApiMaster(object):
    
        def make_request(self, url, method, query_params=None, body=None, logger=None):
            if not logger:
                get_default_logger_somehow()
    
            response = requests.request(method, url, params=query_params, json=body)
            if response.status_code == 400:
                logger.error(response.request.url)
            elif response.status_code == 200:
                try:
                    return reponse.json()
                except SomeError:
                    return None
    
    class Api1(ApiMaster):
        json = self.make_request('post', 'http://example/com')
    

    【讨论】:

    • 谢谢!这是一种非常简洁的处理方式。
    猜你喜欢
    • 2019-09-18
    • 2011-05-22
    • 1970-01-01
    • 2020-07-14
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 2023-03-23
    相关资源
    最近更新 更多