Created
June 4, 2018 08:35
-
-
Save shau-lok/2ffe62f9b4ae5a0fe378c164bdab9dbe to your computer and use it in GitHub Desktop.
flask hook 请求和返回, 为了输出日志
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from json import JSONDecodeError | |
from logging.config import dictConfig | |
import requests | |
from flask import Flask, jsonify, request | |
from apps.forms import EventForm | |
from apps.tasks import collection_event_task | |
from apps.utils import (config_app, logger, cast_to_form_data, | |
get_user_id_via_token) | |
from config import settings | |
from config.logging_settings import LOGGING_CONF | |
dictConfig(LOGGING_CONF) | |
app = Flask(__name__) | |
config_app(app) | |
@app.before_request | |
def before_request(): | |
http_method = request.method | |
http_path = request.path | |
http_host = request.host | |
logger.info(f'【请求信息】 -> ' | |
f'host: {http_host}; ' | |
f'path: {http_path}; ' | |
f'method: {http_method}; ') | |
logger.info(f'【请求form】 -> {request.form.to_dict()}') | |
logger.info(f'【请求json】 -> {request.json}') | |
logger.info(f'【请求params】 -> {request.args.to_dict()}') | |
@app.after_request | |
def after_request(response): | |
try: | |
result = json.loads(response.data.decode()) | |
except JSONDecodeError: | |
result = response.data.decode() | |
logger.info(f'【返回结果】 -> {result}') | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment