Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用错误代码记录所有http响应>=400_Python_Http_Flask_Swagger - Fatal编程技术网

Python 使用错误代码记录所有http响应>=400

Python 使用错误代码记录所有http响应>=400,python,http,flask,swagger,Python,Http,Flask,Swagger,所讨论的应用程序使用包装flask的。该API是用swagger指定的。有没有一种简单而直接的方法可以从web服务器得到http响应的代码 如果可能的话,我想避免写200个错误处理程序,或者10个最流行的错误处理程序 api.py import connexion app = connexion.App(__name__, specification_dir='../swagger/', swagger_ui=False,

所讨论的应用程序使用包装flask的。该API是用swagger指定的。有没有一种简单而直接的方法可以从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
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__)
招摇过市.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"

正如davidism所建议的,我通过对Flask对象进行子类化来解决这个问题。简短版本如下:

app.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
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__)
会话日志

./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 -

如果有人知道如何访问触发当前响应的请求,请随意发表评论,这样我也可以将其包含在这个回答中。

我按照davidism的建议,通过对Flask对象进行子类化解决了这个问题。简短版本如下:

app.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
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__)
会话日志

./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 -
如果有人知道如何访问触发当前响应的请求,请随意发表评论,这样我也可以将其包含在这个回答中