This repository was archived by the owner on Apr 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublic.py
More file actions
65 lines (55 loc) · 2.02 KB
/
Copy pathpublic.py
File metadata and controls
65 lines (55 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from typing import Union
from flask import Flask, jsonify, current_app, request
import asyncio
import logging
import time
from pydantic import ValidationError
def init_app(app: Flask):
gunicorn_logger = logging.getLogger('gunicorn.error')
if gunicorn_logger.hasHandlers():
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
app.before_request(request_info)
app.register_error_handler(Exception, handle_exception)
# test page
@app.get("/")
def test_get():
return "<p>Hello, World!</p>"
@app.route("/async")
async def test_async():
await asyncio.sleep(5)
return jsonify('async')
@app.route("/delay")
def test_block():
time.sleep(5)
return jsonify('delay')
def request_info():
"""Debugger for request info"""
try:
if request.content_type == 'application/json':
data = request.json
elif request.content_type == 'application/x-tar':
data = 'application/x-tar'
else:
data = request.data
current_app.logger.debug(f'\n view_args: {request.view_args}\
\n data : {data}\
\n args : {request.args.to_dict()}')
# current_app.logger.debug(f'\n header : {request.headers}\
# \n addr : {request.remote_addr}')
except:
pass
def handle_exception(e: Union[Exception, ValidationError]):
"""flask error handler"""
current_app.logger.error(e)
# current_app.logger.error(e.args)
if type(e) == ValidationError:
arg: dict = {}
if (len(raw_errors := e.raw_errors) == 1):
if (args := raw_errors[0].exc.args):
arg = args[0]
msgCode = arg.get('msgCode', 'validationError')
msg = arg.get('msg', str(e))
return jsonify({'msgCode': msgCode, 'msg': msg}), 400
else:
return jsonify({'msgCode': 'unexpectedError', 'msg': str(e)}), 400