-
Notifications
You must be signed in to change notification settings - Fork 0
/
v4.py
66 lines (45 loc) · 1.58 KB
/
v4.py
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
66
import logging.config
import time
import uuid
from functools import wraps
from flask import Request, Flask, request
from flask.views import MethodView
from common import get_logging_config
logging.config.dictConfig(get_logging_config())
class MyRequest(Request):
def __init__(self, environ: "WSGIEnvironment", populate_request: bool = True, shallow: bool = False) -> None:
super().__init__(environ, populate_request, shallow)
self.__context = {}
@property
def context(self):
return self.__context
def add_context(self, key, value):
self.__context[key] = value
class MyFlask(Flask):
request_class = MyRequest
class RequestContextLogger:
def __init__(self, logger):
self.__logger = logger
def info(self, message):
self.__logger.info(message, extra=request.context)
def add_request_id(logger):
def decorator(f):
@wraps(f)
def decorated_function(self):
request_id = uuid.uuid4()
request.add_context('request_id', request_id)
logger.info(f'hello from middleware ({request_id})')
return f(self, request_id)
return decorated_function
return decorator
class HelloView(MethodView):
logger = RequestContextLogger(logging.getLogger('view.hello'))
@add_request_id(logger)
def get(self, request_id):
time.sleep(0.01)
self.logger.info(f'hello from view ({request_id})')
return 'Hello World'
app = MyFlask(__name__)
app.add_url_rule('/', view_func=HelloView.as_view('hello'))
if __name__ == '__main__':
app.run()