|
1
|
|
|
from typing import Optional, Type |
|
2
|
|
|
|
|
3
|
|
|
from flask import current_app, g |
|
4
|
|
|
from pydantic import BaseModel |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
class _ContextLocalData: |
|
8
|
|
|
def __init__(self, key_name, default): |
|
9
|
|
|
self.key_name = key_name |
|
10
|
|
|
self.default = default |
|
11
|
|
|
|
|
12
|
|
|
def get(self, _g): |
|
13
|
|
|
return getattr(_g, self.key_name, self.default) |
|
14
|
|
|
|
|
15
|
|
|
def set(self, _g, value): |
|
16
|
|
|
setattr(_g, self.key_name, value) |
|
17
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
class _ContextProperty: |
|
20
|
|
|
class ContextLocalData: |
|
21
|
|
|
request_path_params = _ContextLocalData("request_path_params", None) |
|
22
|
|
|
request_query_params = _ContextLocalData("request_query_params", None) |
|
23
|
|
|
request_json = _ContextLocalData("request_json", None) |
|
24
|
|
|
|
|
25
|
|
|
@property |
|
26
|
|
|
def secret_key(self) -> str: |
|
27
|
|
|
return current_app.secret_key |
|
28
|
|
|
|
|
29
|
|
|
# - request payload - |
|
30
|
|
|
|
|
31
|
|
|
@property |
|
32
|
|
|
def request_path_params(self) -> Optional[BaseModel]: |
|
33
|
|
|
return self.ContextLocalData.request_path_params.get(g) |
|
34
|
|
|
|
|
35
|
|
|
@request_path_params.setter |
|
36
|
|
|
def request_path_params(self, value: Type[BaseModel]): |
|
37
|
|
|
self.ContextLocalData.request_path_params.set(g, value) |
|
38
|
|
|
|
|
39
|
|
|
@property |
|
40
|
|
|
def request_query_params(self) -> Optional[BaseModel]: |
|
41
|
|
|
return self.ContextLocalData.request_query_params.get(g) |
|
42
|
|
|
|
|
43
|
|
|
@request_query_params.setter |
|
44
|
|
|
def request_query_params(self, value: Type[BaseModel]): |
|
45
|
|
|
self.ContextLocalData.request_query_params.set(g, value) |
|
46
|
|
|
|
|
47
|
|
|
@property |
|
48
|
|
|
def request_json(self) -> Optional[BaseModel]: |
|
49
|
|
|
return self.ContextLocalData.request_json.get(g) |
|
50
|
|
|
|
|
51
|
|
|
@request_json.setter |
|
52
|
|
|
def request_json(self, value: Type[BaseModel]): |
|
53
|
|
|
self.ContextLocalData.request_json.set(g, value) |
|
54
|
|
|
|
|
55
|
|
|
|
|
56
|
|
|
context_property = _ContextProperty() |
|
57
|
|
|
|