flarchitect 0.0.8.1__tar.gz

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.
Files changed (53) hide show
  1. flarchitect-0.0.8.1/LICENCE.rst +19 -0
  2. flarchitect-0.0.8.1/PKG-INFO +31 -0
  3. flarchitect-0.0.8.1/README.md +0 -0
  4. flarchitect-0.0.8.1/flarchitect/__init__.py +0 -0
  5. flarchitect-0.0.8.1/flarchitect/core/__init__.py +0 -0
  6. flarchitect-0.0.8.1/flarchitect/core/architect.py +273 -0
  7. flarchitect-0.0.8.1/flarchitect/core/routes.py +886 -0
  8. flarchitect-0.0.8.1/flarchitect/core/utils.py +108 -0
  9. flarchitect-0.0.8.1/flarchitect/database/__init__.py +0 -0
  10. flarchitect-0.0.8.1/flarchitect/database/operations.py +581 -0
  11. flarchitect-0.0.8.1/flarchitect/database/utils.py +824 -0
  12. flarchitect-0.0.8.1/flarchitect/exceptions.py +82 -0
  13. flarchitect-0.0.8.1/flarchitect/html/apispec.html +27 -0
  14. flarchitect-0.0.8.1/flarchitect/html/base_readme.MD +112 -0
  15. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/__init__.py +0 -0
  16. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/aggregate.html +22 -0
  17. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/fields.html +32 -0
  18. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/filters.html +29 -0
  19. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/group.html +21 -0
  20. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/joins.html +30 -0
  21. flarchitect-0.0.8.1/flarchitect/html/redoc_templates/order.html +15 -0
  22. flarchitect-0.0.8.1/flarchitect/logging.py +64 -0
  23. flarchitect-0.0.8.1/flarchitect/schemas/__init__.py +0 -0
  24. flarchitect-0.0.8.1/flarchitect/schemas/bases.py +548 -0
  25. flarchitect-0.0.8.1/flarchitect/schemas/models.py +169 -0
  26. flarchitect-0.0.8.1/flarchitect/schemas/utils.py +162 -0
  27. flarchitect-0.0.8.1/flarchitect/schemas/validators.py +139 -0
  28. flarchitect-0.0.8.1/flarchitect/specs/__init__.py +0 -0
  29. flarchitect-0.0.8.1/flarchitect/specs/base.py +0 -0
  30. flarchitect-0.0.8.1/flarchitect/specs/generator.py +439 -0
  31. flarchitect-0.0.8.1/flarchitect/specs/utils.py +1258 -0
  32. flarchitect-0.0.8.1/flarchitect/utils/__init__.py +0 -0
  33. flarchitect-0.0.8.1/flarchitect/utils/config_helpers.py +108 -0
  34. flarchitect-0.0.8.1/flarchitect/utils/core_utils.py +76 -0
  35. flarchitect-0.0.8.1/flarchitect/utils/decorators.py +289 -0
  36. flarchitect-0.0.8.1/flarchitect/utils/general.py +418 -0
  37. flarchitect-0.0.8.1/flarchitect/utils/response_filters.py +35 -0
  38. flarchitect-0.0.8.1/flarchitect/utils/response_helpers.py +85 -0
  39. flarchitect-0.0.8.1/flarchitect/utils/responses.py +93 -0
  40. flarchitect-0.0.8.1/flarchitect.egg-info/PKG-INFO +31 -0
  41. flarchitect-0.0.8.1/flarchitect.egg-info/SOURCES.txt +51 -0
  42. flarchitect-0.0.8.1/flarchitect.egg-info/dependency_links.txt +1 -0
  43. flarchitect-0.0.8.1/flarchitect.egg-info/requires.txt +23 -0
  44. flarchitect-0.0.8.1/flarchitect.egg-info/top_level.txt +1 -0
  45. flarchitect-0.0.8.1/setup.cfg +4 -0
  46. flarchitect-0.0.8.1/setup.py +27 -0
  47. flarchitect-0.0.8.1/tests/test_api_filters.py +111 -0
  48. flarchitect-0.0.8.1/tests/test_basic.py +149 -0
  49. flarchitect-0.0.8.1/tests/test_exceptions.py +86 -0
  50. flarchitect-0.0.8.1/tests/test_flask.py +26 -0
  51. flarchitect-0.0.8.1/tests/test_flask_config.py +704 -0
  52. flarchitect-0.0.8.1/tests/test_functions.py +372 -0
  53. flarchitect-0.0.8.1/tests/test_models.py +31 -0
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2024 Lewis Morris
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.1
2
+ Name: flarchitect
3
+ Version: 0.0.8.1
4
+ Summary: Automatic RESTful API generator with redoc
5
+ Author: arched.dev (Lewis Morris)
6
+ Author-email: hello@arched.dev
7
+ License: MIT
8
+ License-File: LICENCE.rst
9
+ Requires-Dist: colorama==0.4.6
10
+ Requires-Dist: numpy==1.26.4
11
+ Requires-Dist: pytest==8.0.1
12
+ Requires-Dist: requests~=2.32.0
13
+ Requires-Dist: bs4~=0.0.2
14
+ Requires-Dist: beautifulsoup4~=4.12.3
15
+ Requires-Dist: apispec==6.4.0
16
+ Requires-Dist: Flask==3.0.2
17
+ Requires-Dist: Jinja2==3.1.3
18
+ Requires-Dist: marshmallow==3.20.2
19
+ Requires-Dist: pytz==2024.1
20
+ Requires-Dist: setuptools~=68.2.0
21
+ Requires-Dist: Werkzeug~=3.0.1
22
+ Requires-Dist: PyJWT~=2.8.0
23
+ Requires-Dist: inflect~=7.0.0
24
+ Requires-Dist: validators~=0.22.0
25
+ Requires-Dist: flask_limiter~=1.4.0
26
+ Requires-Dist: marshmallow_sqlalchemy~=1.0.0
27
+ Requires-Dist: flask-sqlalchemy
28
+ Requires-Dist: redis>5.0.0
29
+ Requires-Dist: flask-login
30
+ Requires-Dist: flask-jwt-extended
31
+ Requires-Dist: dicttoxml
File without changes
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)