记录所有http响应,错误代码> = 400

时间:2017-10-09 14:57:49

标签: python http flask swagger

有问题的应用程序使用包含瓶子的connexion来处理Web服务器。使用swagger指定API。是否有一种简单直接的方法可以从代码中获取从Web服务器生成http响应的代码?

如果可能的话,我想避免写200个错误处理程序,或者最流行的10个错误处理程序。

api.py

import connexion
app = connexion.App(__name__,
                specification_dir='../swagger/',
                swagger_ui=False,
                validator_map={
                    'body': connexion.decorators.validation.RequestBodyValidator
                })
app.add_api('swagger.yml', strict_validation=True)

# If I had to use app.error_handler decorators to implement the special
# treatment of http responses with error codes, I would put it here

swagger.yml

swagger: '2.0'
info:
  title: My Minimal Working Example
consumes:

  - application/json
produces:
  - application/json

basePath: /api/v1
paths:
  '/do_something':
    post:
      tags:
        - MyTag
      operationId: entrypoint.do_something
      summary: Do something on request
      parameters:
        - name: data
          in: body
          schema:
            $ref: '#/definitions/data'
      responses:
        '200':
          description: Success!
          schema:
            $ref: '#/definitions/Response'
        '400':
          description: Error!
          schema:
            $ref: '#/definitions/Response'
        '403':
          description: Not Authorized
          schema:
            $ref: '#/definitions/Response'    
# a lot more stuff and "definitions"

1 个答案:

答案 0 :(得分:2)

我通过继承Flask对象解决了这个问题,正如davidism建议的那样。简短的版本是:

<强> app.py

import logging.config
import yaml

logging.config.dictConfig(yaml.load(open('logging.conf', 'r')))
logger = logging.getLogger("mainLogger")


class LoggingFlask(Flask):
    def make_response(self, rv):
        rv = super(LoggingFlask, self).make_response(rv)
        if int(rv.status_code) >= 300:
            logger.warn("Request failed with error code %s." % rv.status_code)
        return rv


app = LoggingFlask(__name__)

<强> SESSION.LOG

./app.py 
[2017-10-10 11:38:19,564 - werkzeug - INFO]:  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-10-10 11:38:19,566 - werkzeug - INFO]:  * Restarting with stat
[2017-10-10 11:38:19,690 - werkzeug - WARNING]:  * Debugger is active!
[2017-10-10 11:38:19,691 - werkzeug - INFO]:  * Debugger PIN: 211-310-838

# issues a good request
[2017-10-10 11:38:25,179 - werkzeug - INFO]: 127.0.0.1 - - [10/Oct/2017 11:38:25] "GET /todo/api/v1.0/tasks HTTP/1.1" 200 -

# issued a bad request
[2017-10-10 11:38:28,646 - mainLogger - WARNING]: Request failed with error code 404.
[2017-10-10 11:38:28,646 - mainLogger - WARNING]: Request failed with error code 404.
[2017-10-10 11:38:28,647 - werkzeug - INFO]: 127.0.0.1 - - [10/Oct/2017 11:38:28] "GET /todo/api/v1.0/task HTTP/1.1" 404 -

如果有人知道如何访问触发当前响应的请求,请随时删除评论,以便我也可以将其包含在此答案中。