flarchitect 0.0.8.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flarchitect/__init__.py +0 -0
- flarchitect/core/__init__.py +0 -0
- flarchitect/core/architect.py +273 -0
- flarchitect/core/routes.py +886 -0
- flarchitect/core/utils.py +108 -0
- flarchitect/database/__init__.py +0 -0
- flarchitect/database/operations.py +581 -0
- flarchitect/database/utils.py +824 -0
- flarchitect/exceptions.py +82 -0
- flarchitect/html/apispec.html +27 -0
- flarchitect/html/base_readme.MD +112 -0
- flarchitect/html/redoc_templates/__init__.py +0 -0
- flarchitect/html/redoc_templates/aggregate.html +22 -0
- flarchitect/html/redoc_templates/fields.html +32 -0
- flarchitect/html/redoc_templates/filters.html +29 -0
- flarchitect/html/redoc_templates/group.html +21 -0
- flarchitect/html/redoc_templates/joins.html +30 -0
- flarchitect/html/redoc_templates/order.html +15 -0
- flarchitect/logging.py +64 -0
- flarchitect/schemas/__init__.py +0 -0
- flarchitect/schemas/bases.py +548 -0
- flarchitect/schemas/models.py +169 -0
- flarchitect/schemas/utils.py +162 -0
- flarchitect/schemas/validators.py +139 -0
- flarchitect/specs/__init__.py +0 -0
- flarchitect/specs/base.py +0 -0
- flarchitect/specs/generator.py +439 -0
- flarchitect/specs/utils.py +1258 -0
- flarchitect/utils/__init__.py +0 -0
- flarchitect/utils/config_helpers.py +108 -0
- flarchitect/utils/core_utils.py +76 -0
- flarchitect/utils/decorators.py +289 -0
- flarchitect/utils/general.py +418 -0
- flarchitect/utils/response_filters.py +35 -0
- flarchitect/utils/response_helpers.py +85 -0
- flarchitect/utils/responses.py +93 -0
- flarchitect-0.0.8.1.dist-info/LICENCE.rst +19 -0
- flarchitect-0.0.8.1.dist-info/METADATA +32 -0
- flarchitect-0.0.8.1.dist-info/RECORD +41 -0
- flarchitect-0.0.8.1.dist-info/WHEEL +5 -0
- flarchitect-0.0.8.1.dist-info/top_level.txt +1 -0
flarchitect/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import os
|
|
3
|
+
from functools import wraps
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional, List, Type, Callable
|
|
6
|
+
|
|
7
|
+
from flask import Flask
|
|
8
|
+
from flask_jwt_extended import jwt_required
|
|
9
|
+
from flask_limiter import Limiter
|
|
10
|
+
from flask_limiter.util import get_remote_address
|
|
11
|
+
from marshmallow import Schema
|
|
12
|
+
from sqlalchemy.orm import DeclarativeBase
|
|
13
|
+
|
|
14
|
+
from flarchitect.logging import logger
|
|
15
|
+
from flarchitect.utils.general import (
|
|
16
|
+
AttributeInitializerMixin,
|
|
17
|
+
check_rate_services,
|
|
18
|
+
validate_flask_limiter_rate_limit_string,
|
|
19
|
+
)
|
|
20
|
+
from flarchitect.utils.config_helpers import get_config_or_model_meta
|
|
21
|
+
from flarchitect.utils.decorators import handle_many, handle_one
|
|
22
|
+
from flarchitect.core.routes import find_rule_by_function, RouteCreator
|
|
23
|
+
from flarchitect.specs.generator import CustomSpec
|
|
24
|
+
|
|
25
|
+
FLASK_APP_NAME = "flarchitect"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Architect(AttributeInitializerMixin):
|
|
29
|
+
app: Flask
|
|
30
|
+
api_spec: Optional[CustomSpec] = None
|
|
31
|
+
api: Optional["RouteCreator"] = None
|
|
32
|
+
base_dir: str = os.path.dirname(os.path.abspath(__file__))
|
|
33
|
+
route_spec: List = []
|
|
34
|
+
limiter: Limiter
|
|
35
|
+
|
|
36
|
+
def __init__(self, app: Optional[Flask] = None, *args, **kwargs):
|
|
37
|
+
"""
|
|
38
|
+
Initializes the Architect object.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
app (Flask): The flask app.
|
|
42
|
+
*args (list): List of arguments.
|
|
43
|
+
**kwargs (dict): Dictionary of keyword arguments.
|
|
44
|
+
"""
|
|
45
|
+
if app is not None:
|
|
46
|
+
self.init_app(app, *args, **kwargs)
|
|
47
|
+
logger.verbosity_level = self.get_config("API_VERBOSITY_LEVEL", 0)
|
|
48
|
+
|
|
49
|
+
def init_app(self, app: Flask, *args, **kwargs):
|
|
50
|
+
"""
|
|
51
|
+
Initializes the Architect object.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
app (Flask): The flask app.
|
|
55
|
+
*args (list): List of arguments.
|
|
56
|
+
**kwargs (dict): Dictionary of keyword arguments.
|
|
57
|
+
"""
|
|
58
|
+
super().__init__(app=app, *args, **kwargs)
|
|
59
|
+
self._register_app(app)
|
|
60
|
+
logger.verbosity_level = self.get_config("API_VERBOSITY_LEVEL", 0)
|
|
61
|
+
self.api_spec = None
|
|
62
|
+
|
|
63
|
+
if self.get_config("FULL_AUTO", True):
|
|
64
|
+
self.init_api(app=app, **kwargs)
|
|
65
|
+
if get_config_or_model_meta("API_CREATE_DOCS", default=True):
|
|
66
|
+
self.init_apispec(app=app, **kwargs)
|
|
67
|
+
|
|
68
|
+
logger.log(2, "Creating rate limiter")
|
|
69
|
+
storage_uri = check_rate_services()
|
|
70
|
+
self.app.config["RATELIMIT_HEADERS_ENABLED"] = True
|
|
71
|
+
self.app.config["RATELIMIT_SWALLOW_ERRORS"] = True
|
|
72
|
+
self.app.config["RATELIMIT_IN_MEMORY_FALLBACK_ENABLED"] = True
|
|
73
|
+
self.limiter = Limiter(
|
|
74
|
+
app=app,
|
|
75
|
+
key_func=get_remote_address,
|
|
76
|
+
storage_uri=storage_uri if storage_uri else None,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def _register_app(self, app: Flask):
|
|
80
|
+
"""
|
|
81
|
+
Registers the app with the extension, and saves it to self.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
app (Flask): The flask app.
|
|
85
|
+
"""
|
|
86
|
+
if FLASK_APP_NAME not in app.extensions:
|
|
87
|
+
app.extensions[FLASK_APP_NAME] = self
|
|
88
|
+
self.app = app
|
|
89
|
+
|
|
90
|
+
def init_apispec(self, app: Flask, **kwargs):
|
|
91
|
+
"""
|
|
92
|
+
Initializes the api spec object.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
app (Flask): The flask app.
|
|
96
|
+
**kwargs (dict): Dictionary of keyword arguments.
|
|
97
|
+
"""
|
|
98
|
+
self.api_spec = CustomSpec(app=app, architect=self, **kwargs)
|
|
99
|
+
|
|
100
|
+
def init_api(self, **kwargs):
|
|
101
|
+
"""
|
|
102
|
+
Initializes the api object, which handles flask route creation for models.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
**kwargs (dict): Dictionary of keyword arguments.
|
|
106
|
+
"""
|
|
107
|
+
self.api = RouteCreator(architect=self, **kwargs)
|
|
108
|
+
|
|
109
|
+
def to_api_spec(self):
|
|
110
|
+
"""
|
|
111
|
+
Returns the api spec object.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
APISpec: The api spec json object.
|
|
115
|
+
"""
|
|
116
|
+
if self.api_spec:
|
|
117
|
+
return self.api_spec.to_dict()
|
|
118
|
+
|
|
119
|
+
def get_config(self, key, default: Optional = None):
|
|
120
|
+
"""
|
|
121
|
+
Gets a config value from the app config.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
key (str): The key of the config value.
|
|
125
|
+
default (Optional): The default value to return if the key is not found.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
Any: The config value.
|
|
129
|
+
"""
|
|
130
|
+
if self.app:
|
|
131
|
+
return self.app.config.get(key, default)
|
|
132
|
+
|
|
133
|
+
def schema_constructor(
|
|
134
|
+
self,
|
|
135
|
+
output_schema: Optional[Type[Schema]] = None,
|
|
136
|
+
input_schema: Optional[Type[Schema]] = None,
|
|
137
|
+
model: Optional[DeclarativeBase] = None,
|
|
138
|
+
group_tag: Optional[str] = None,
|
|
139
|
+
many: Optional[bool] = False,
|
|
140
|
+
**kwargs,
|
|
141
|
+
) -> Callable:
|
|
142
|
+
"""
|
|
143
|
+
Decorator to specify OpenAPI metadata for an endpoint, along with schema information for the input and output.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
output_schema (Optional[Type[Schema]], optional): Output schema. Defaults to None.
|
|
147
|
+
input_schema (Optional[Type[Schema]], optional): Input schema. Defaults to None.
|
|
148
|
+
model (Optional[DeclarativeBase], optional): Database model. Defaults to None.
|
|
149
|
+
group_tag (Optional[str], optional): Group name. Defaults to None.
|
|
150
|
+
many (Optional[Bool], optional): Is many or one? Defaults to False
|
|
151
|
+
kwargs (dict): Dictionary of keyword arguments.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
Callable: The decorated function.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
def decorator(f: Callable) -> Callable:
|
|
158
|
+
@wraps(f)
|
|
159
|
+
def wrapped(*_args, **_kwargs):
|
|
160
|
+
f_decorated = f
|
|
161
|
+
|
|
162
|
+
auth_method = get_config_or_model_meta(
|
|
163
|
+
"API_AUTHENTICATE",
|
|
164
|
+
model=model,
|
|
165
|
+
output_schema=output_schema,
|
|
166
|
+
input_schema=input_schema,
|
|
167
|
+
default=False,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def jwt_authentication(func):
|
|
171
|
+
@wraps(func)
|
|
172
|
+
@jwt_required()
|
|
173
|
+
def auth_wrapped(*args, **kwargs):
|
|
174
|
+
return func(*args, **kwargs)
|
|
175
|
+
|
|
176
|
+
return auth_wrapped
|
|
177
|
+
|
|
178
|
+
if auth_method == "jwt":
|
|
179
|
+
f_decorated = jwt_authentication(f_decorated)
|
|
180
|
+
elif auth_method == "basic":
|
|
181
|
+
f_decorated = None # authentication(f_decorated)
|
|
182
|
+
elif auth_method == "api_key":
|
|
183
|
+
f_decorated = None # authentication(f_decorated)
|
|
184
|
+
|
|
185
|
+
f_decorated = (
|
|
186
|
+
handle_many(output_schema, input_schema)(f_decorated)
|
|
187
|
+
if many
|
|
188
|
+
else handle_one(output_schema, input_schema)(f_decorated)
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
rl = get_config_or_model_meta(
|
|
192
|
+
"API_RATE_LIMIT",
|
|
193
|
+
model=model,
|
|
194
|
+
input_schema=input_schema,
|
|
195
|
+
output_schema=output_schema,
|
|
196
|
+
default=False,
|
|
197
|
+
)
|
|
198
|
+
if (
|
|
199
|
+
rl
|
|
200
|
+
and isinstance(rl, str)
|
|
201
|
+
and validate_flask_limiter_rate_limit_string(rl)
|
|
202
|
+
):
|
|
203
|
+
f_decorated = self.limiter.limit(rl)(f_decorated)
|
|
204
|
+
elif rl:
|
|
205
|
+
rule = find_rule_by_function(self, f).rule
|
|
206
|
+
logger.error(
|
|
207
|
+
f"Rate limit definition not a string or not valid. Skipping for `{rule}` route."
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
result = f_decorated(*_args, **_kwargs)
|
|
211
|
+
return result
|
|
212
|
+
|
|
213
|
+
route_info = {
|
|
214
|
+
"function": wrapped,
|
|
215
|
+
"output_schema": output_schema,
|
|
216
|
+
"input_schema": input_schema,
|
|
217
|
+
"model": model,
|
|
218
|
+
"group_tag": group_tag,
|
|
219
|
+
"tag": kwargs.get("tag"),
|
|
220
|
+
"summary": kwargs.get("summary"),
|
|
221
|
+
"error_responses": kwargs.get("error_responses"),
|
|
222
|
+
"many_to_many_model": kwargs.get("many_to_many_model"),
|
|
223
|
+
"multiple": many or kwargs.get("multiple"),
|
|
224
|
+
"parent": kwargs.get("parent_model"),
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
self.set_route(route_info)
|
|
228
|
+
return wrapped
|
|
229
|
+
|
|
230
|
+
return decorator
|
|
231
|
+
|
|
232
|
+
@classmethod
|
|
233
|
+
def get_templates_path(cls, folder_name="html", max_levels=3):
|
|
234
|
+
"""
|
|
235
|
+
Recursively searches for the folder_name in the source directory
|
|
236
|
+
or its parent directories up to max_levels levels.
|
|
237
|
+
|
|
238
|
+
Args:
|
|
239
|
+
folder_name (str): The name of the folder to search for. Default is "html".
|
|
240
|
+
max_levels (int): Maximum number of levels to search upwards. Default is 3.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
str: The path to the folder if found, else None.
|
|
244
|
+
"""
|
|
245
|
+
# Find the source directory of the class/module
|
|
246
|
+
spec = importlib.util.find_spec(cls.__module__)
|
|
247
|
+
source_dir = Path(os.path.split(spec.origin)[0])
|
|
248
|
+
|
|
249
|
+
# Traverse up to max_levels levels
|
|
250
|
+
for level in range(max_levels):
|
|
251
|
+
# Search for the folder in the current directory
|
|
252
|
+
potential_path = source_dir / folder_name
|
|
253
|
+
if potential_path.exists() and potential_path.is_dir():
|
|
254
|
+
return str(potential_path)
|
|
255
|
+
|
|
256
|
+
# Move to the parent directory for the next level search
|
|
257
|
+
source_dir = source_dir.parent
|
|
258
|
+
|
|
259
|
+
# Return None if the folder is not found
|
|
260
|
+
return None
|
|
261
|
+
|
|
262
|
+
def set_route(self, route: dict):
|
|
263
|
+
"""
|
|
264
|
+
Adds a route to the route spec list, which is used to generate the api spec.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
route (dict): The route object.
|
|
268
|
+
"""
|
|
269
|
+
if not hasattr(route["function"], "_decorators"):
|
|
270
|
+
route["function"]._decorators = []
|
|
271
|
+
|
|
272
|
+
route["function"]._decorators.append(self.schema_constructor)
|
|
273
|
+
self.route_spec.append(route)
|