2017-10-09 24 views
0

有問題的應用程序使用connexion包裝燒瓶來照顧網絡服務器。這個API是用swagger指定的。有沒有一種簡單直接的方法可以讓代碼從http服務器制定http響應?記錄所有http響應的錯誤代碼大於等於400

如果可能的話,我想避免編寫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

如果你不是直接編寫代碼,只是使用大招,那麼你只能限於swagger可以做的事情。否則,可以繼承Flask的子類並覆蓋它的錯誤處理。不知道Swagger或Connexion,我不知道這是否可能在你的情況。你有對Flask類或應用程序實例的控制嗎? – davidism

+0

我直接編寫代碼並控制應用程序實例 – Arne

+0

請[edit]包含一個[mcve]來證明這一點。 – davidism

回答

1

我通過繼承瓶對象解決了這個問題,作爲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 - 

如果有人知道如何訪問觸發電流響應的要求,隨意刪除評論,以便我可以將其納入此答案中。

相關問題