flask-openapi 4.3.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.
Files changed (53) hide show
  1. flask_openapi/__init__.py +44 -0
  2. flask_openapi/__version__.py +5 -0
  3. flask_openapi/blueprint.py +201 -0
  4. flask_openapi/commands.py +38 -0
  5. flask_openapi/models/__init__.py +91 -0
  6. flask_openapi/models/callback.py +18 -0
  7. flask_openapi/models/components.py +37 -0
  8. flask_openapi/models/contact.py +17 -0
  9. flask_openapi/models/data_type.py +18 -0
  10. flask_openapi/models/discriminator.py +16 -0
  11. flask_openapi/models/encoding.py +27 -0
  12. flask_openapi/models/example.py +19 -0
  13. flask_openapi/models/external_documentation.py +16 -0
  14. flask_openapi/models/file.py +27 -0
  15. flask_openapi/models/header.py +17 -0
  16. flask_openapi/models/info.py +24 -0
  17. flask_openapi/models/license.py +17 -0
  18. flask_openapi/models/link.py +23 -0
  19. flask_openapi/models/media_type.py +24 -0
  20. flask_openapi/models/oauth_flow.py +18 -0
  21. flask_openapi/models/oauth_flows.py +20 -0
  22. flask_openapi/models/operation.py +36 -0
  23. flask_openapi/models/parameter.py +34 -0
  24. flask_openapi/models/parameter_in_type.py +13 -0
  25. flask_openapi/models/path_item.py +36 -0
  26. flask_openapi/models/paths.py +9 -0
  27. flask_openapi/models/reference.py +14 -0
  28. flask_openapi/models/request_body.py +19 -0
  29. flask_openapi/models/response.py +23 -0
  30. flask_openapi/models/responses.py +11 -0
  31. flask_openapi/models/schema.py +59 -0
  32. flask_openapi/models/security_requirement.py +8 -0
  33. flask_openapi/models/security_scheme.py +25 -0
  34. flask_openapi/models/security_scheme_in_type.py +12 -0
  35. flask_openapi/models/server.py +19 -0
  36. flask_openapi/models/server_variable.py +17 -0
  37. flask_openapi/models/style_values.py +14 -0
  38. flask_openapi/models/tag.py +15 -0
  39. flask_openapi/models/validation_error.py +24 -0
  40. flask_openapi/models/xml.py +19 -0
  41. flask_openapi/openapi.py +449 -0
  42. flask_openapi/plugins.py +17 -0
  43. flask_openapi/py.typed +0 -0
  44. flask_openapi/request.py +250 -0
  45. flask_openapi/scaffold.py +547 -0
  46. flask_openapi/templates.py +113 -0
  47. flask_openapi/types.py +27 -0
  48. flask_openapi/utils.py +633 -0
  49. flask_openapi/view.py +230 -0
  50. flask_openapi-4.3.1.dist-info/METADATA +258 -0
  51. flask_openapi-4.3.1.dist-info/RECORD +53 -0
  52. flask_openapi-4.3.1.dist-info/WHEEL +4 -0
  53. flask_openapi-4.3.1.dist-info/licenses/LICENSE.rst +21 -0
@@ -0,0 +1,449 @@
1
+ # -*- coding: utf-8 -*-
2
+ # @Author : llc
3
+ # @Time : 2021/4/30 14:25
4
+ import os
5
+ import re
6
+ from importlib import import_module
7
+ from importlib.metadata import entry_points
8
+ from typing import Any, Callable, Type
9
+
10
+ from flask import Blueprint, Flask, render_template_string
11
+ from pydantic import BaseModel
12
+
13
+ from .blueprint import APIBlueprint
14
+ from .commands import openapi_command
15
+ from .models import (
16
+ OPENAPI3_REF_PREFIX,
17
+ APISpec,
18
+ Components,
19
+ ExternalDocumentation,
20
+ Info,
21
+ Schema,
22
+ Server,
23
+ Tag,
24
+ ValidationErrorModel,
25
+ )
26
+ from .scaffold import APIScaffold
27
+ from .templates import openapi_html_string
28
+ from .types import ParametersTuple, ResponseDict, SecuritySchemesDict
29
+ from .utils import (
30
+ HTTP_STATUS,
31
+ HTTPMethod,
32
+ convert_responses_key_to_string,
33
+ get_model_schema,
34
+ get_operation,
35
+ get_operation_id_for_path,
36
+ get_responses,
37
+ make_validation_error_response,
38
+ parse_and_store_tags,
39
+ parse_method,
40
+ parse_parameters,
41
+ run_validate_response,
42
+ )
43
+ from .view import APIView
44
+
45
+
46
+ class OpenAPI(APIScaffold, Flask):
47
+ def __init__(
48
+ self,
49
+ import_name: str,
50
+ *,
51
+ info: Info | None = None,
52
+ security_schemes: SecuritySchemesDict | None = None,
53
+ responses: ResponseDict | None = None,
54
+ servers: list[Server] | None = None,
55
+ external_docs: ExternalDocumentation | None = None,
56
+ operation_id_callback: Callable = get_operation_id_for_path,
57
+ openapi_extensions: dict[str, Any] | None = None,
58
+ validation_error_status: str | int = 422,
59
+ validation_error_model: Type[BaseModel] = ValidationErrorModel,
60
+ validation_error_callback: Callable = make_validation_error_response,
61
+ doc_ui: bool = True,
62
+ doc_prefix: str = "/openapi",
63
+ doc_url: str = "/openapi.json",
64
+ validate_response: bool | None = None,
65
+ validate_response_callback: Callable = run_validate_response,
66
+ **kwargs: Any,
67
+ ) -> None:
68
+ """
69
+ OpenAPI class that provides REST API functionality along with Swagger UI and Redoc.
70
+
71
+ Args:
72
+ import_name: The import name for the Flask application.
73
+ info: Information about the API (title, version, etc.).
74
+ See https://spec.openapis.org/oas/v3.1.0#info-object.
75
+ security_schemes: Security schemes for the API.
76
+ See https://spec.openapis.org/oas/v3.1.0#security-scheme-object.
77
+ responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
78
+ servers: An array of Server objects providing connectivity information to a target server.
79
+ external_docs: External documentation for the API.
80
+ See: https://spec.openapis.org/oas/v3.1.0#external-documentation-object.
81
+ operation_id_callback: Callback function for custom operation ID generation.
82
+ Receives name (str), path (str), and method (str) parameters.
83
+ Defaults to `get_operation_id_for_path` from utils.
84
+ openapi_extensions: Extensions to the OpenAPI Schema.
85
+ See https://spec.openapis.org/oas/v3.1.0#specification-extensions.
86
+ validation_error_status:
87
+ HTTP Status of the response given when a validation error is detected by pydantic.
88
+ Defaults to 422.
89
+ validation_error_model: Validation error response model for OpenAPI Specification.
90
+ validation_error_callback: Validation error response callback, the return format corresponds to
91
+ the validation_error_model.
92
+ doc_ui: Enable OpenAPI document UI (Swagger UI and Redoc).
93
+ Defaults to True.
94
+ doc_prefix: URL prefix used for OpenAPI document and UI.
95
+ Defaults to "/openapi".
96
+ doc_url: URL for accessing the OpenAPI specification document in JSON format.
97
+ Defaults to "/openapi.json".
98
+ validate_response: Verify the response body.
99
+ validate_response_callback: Validation and return response.
100
+ **kwargs: Additional kwargs to be passed to Flask.
101
+ """
102
+ super(OpenAPI, self).__init__(import_name, **kwargs)
103
+
104
+ # Set OpenAPI version and API information
105
+ self.openapi_version = "3.1.0"
106
+ self.info = info or Info(title="OpenAPI", version="1.0.0")
107
+
108
+ # Set security schemes, responses, paths and components
109
+ self.security_schemes = security_schemes
110
+
111
+ # Convert key to string
112
+ self.responses = convert_responses_key_to_string(responses or {})
113
+
114
+ # Initialize instance variables
115
+ self.paths: dict = dict()
116
+ self.components_schemas: dict = dict()
117
+ self.components = Components()
118
+
119
+ # Initialize lists for tags and tag names
120
+ self.tags: list[Tag] = []
121
+ self.tag_names: list[str] = []
122
+
123
+ # Set URL prefixes and endpoints
124
+ self.doc_prefix = doc_prefix
125
+ self.doc_url = doc_url
126
+
127
+ # Set servers and external documentation
128
+ self.severs = servers
129
+ self.external_docs = external_docs
130
+
131
+ # Set the operation ID callback function
132
+ self.operation_id_callback: Callable = operation_id_callback
133
+
134
+ # Set OpenAPI extensions
135
+ self.openapi_extensions = openapi_extensions or {}
136
+
137
+ # Set HTTP Response of validation errors within OpenAPI
138
+ self.validation_error_status = str(validation_error_status)
139
+ self.validation_error_model = validation_error_model
140
+ self.validation_error_callback = validation_error_callback
141
+
142
+ # Initialize the OpenAPI documentation UI
143
+ if doc_ui:
144
+ self._init_doc()
145
+
146
+ # Add the OpenAPI command
147
+ self.cli.add_command(openapi_command) # type: ignore
148
+
149
+ # Verify the response body
150
+ self.validate_response = validate_response
151
+ self.validate_response_callback = validate_response_callback
152
+
153
+ # Initialize specification JSON
154
+ self.spec_json: dict = {}
155
+ self.spec = APISpec(openapi=self.openapi_version, info=self.info, paths=self.paths)
156
+
157
+ def _init_doc(self) -> None:
158
+ """
159
+ Provide Swagger UI, Redoc, and Rapidoc
160
+ """
161
+ _here = os.path.dirname(__file__)
162
+ template_folder = os.path.join(_here, "templates")
163
+ static_folder = os.path.join(template_folder, "static")
164
+
165
+ # Create the blueprint for OpenAPI documentation
166
+ blueprint = Blueprint(
167
+ "openapi",
168
+ __name__,
169
+ url_prefix=self.doc_prefix,
170
+ template_folder=template_folder,
171
+ static_folder=static_folder,
172
+ )
173
+
174
+ # Add the API documentation URL rule
175
+ blueprint.add_url_rule(rule=self.doc_url, endpoint="doc_url", view_func=lambda: self.api_doc)
176
+
177
+ ui_templates = []
178
+ # Iterate over all entry points in the "flask_openapi3.plugins" group
179
+ for entry_point in entry_points(group="flask_openapi3.plugins"):
180
+ try:
181
+ module_path = entry_point.value
182
+ module_name, class_name = module_path.rsplit(".", 1)
183
+ module = import_module(module_name)
184
+ plugin_class = getattr(module, class_name)
185
+ plugin_register = plugin_class.register
186
+ plugin_name = plugin_class.name
187
+ plugin_display_name = plugin_class.display_name
188
+ bp = plugin_register(doc_url=self.doc_url.lstrip("/"))
189
+ self.register_blueprint(bp, url_prefix=self.doc_prefix)
190
+ ui_templates.append({"name": plugin_name, "display_name": plugin_display_name})
191
+ except (ModuleNotFoundError, AttributeError): # pragma: no cover
192
+ import traceback
193
+
194
+ print(f"Warning: plugin '{entry_point.value}' registration failed.")
195
+ traceback.print_exc()
196
+
197
+ # Add URL rule for the home page
198
+ blueprint.add_url_rule(
199
+ rule="/",
200
+ endpoint="openapi",
201
+ view_func=lambda: render_template_string(
202
+ self.config.get("OPENAPI_HTML_STRING") or openapi_html_string, ui_templates=ui_templates
203
+ ),
204
+ )
205
+
206
+ # Register the blueprint with the Flask application
207
+ self.register_blueprint(blueprint)
208
+
209
+ @property
210
+ def api_doc(self) -> dict:
211
+ """
212
+ Generate the OpenAPI specification JSON.
213
+
214
+ Returns:
215
+ The OpenAPI specification JSON as a dictionary.
216
+
217
+ """
218
+ if self.spec_json:
219
+ return self.spec_json
220
+
221
+ self.generate_spec_json()
222
+
223
+ return self.spec_json
224
+
225
+ def generate_spec_json(self):
226
+ self.spec.openapi = self.openapi_version
227
+ self.spec.info = self.info
228
+ self.spec.paths = self.paths
229
+
230
+ if self.severs:
231
+ self.spec.servers = self.severs
232
+
233
+ if self.external_docs:
234
+ self.spec.externalDocs = self.external_docs
235
+
236
+ # Set tags
237
+ if self.tags:
238
+ self.spec.tags = self.tags
239
+
240
+ # Add ValidationErrorModel to components schemas
241
+ schema = get_model_schema(self.validation_error_model)
242
+ self.components_schemas[self.validation_error_model.__name__] = Schema(**schema)
243
+
244
+ # Parse definitions
245
+ definitions = schema.get("$defs", {})
246
+ for name, value in definitions.items():
247
+ self.components_schemas[name] = Schema(**value)
248
+
249
+ # Set components
250
+ self.components.schemas = self.components_schemas
251
+ self.components.securitySchemes = self.security_schemes
252
+ self.spec.components = self.components
253
+
254
+ # Convert spec to JSON
255
+ self.spec_json = self.spec.model_dump(mode="json", by_alias=True, exclude_unset=True, warnings=False)
256
+
257
+ # Update with OpenAPI extensions
258
+ self.spec_json.update(**self.openapi_extensions)
259
+
260
+ # Handle validation error response
261
+ for rule, path_item in self.spec_json["paths"].items():
262
+ for http_method, operation in path_item.items():
263
+ if operation.get("responses") is None:
264
+ operation["responses"] = {}
265
+ if operation["responses"].get(self.validation_error_status):
266
+ continue
267
+ operation["responses"][self.validation_error_status] = {
268
+ "description": HTTP_STATUS[self.validation_error_status],
269
+ "content": {
270
+ "application/json": {
271
+ "schema": {
272
+ "type": "array",
273
+ "items": {"$ref": f"{OPENAPI3_REF_PREFIX}/{self.validation_error_model.__name__}"},
274
+ }
275
+ }
276
+ },
277
+ }
278
+
279
+ def register_api(self, api: APIBlueprint, **options: Any) -> None:
280
+ """
281
+ Register an APIBlueprint.
282
+
283
+ Args:
284
+ api: The APIBlueprint instance to register.
285
+
286
+ options: Additional keyword arguments are passed to :class:`~flask.blueprints.BlueprintSetupState`.
287
+ They can be accessed in :meth:`~flask.Blueprint.record` callbacks.
288
+ url_prefix, Blueprint routes will be prefixed with this.
289
+ subdomain, Blueprint routes will match on this subdomain.
290
+ url_defaults, Blueprint routes will use these default values for view arguments.
291
+
292
+ """
293
+ for tag in api.tags:
294
+ if tag.name not in self.tag_names:
295
+ # Append tag to the list of tags
296
+ self.tags.append(tag)
297
+
298
+ # Append tag name to the list of tag names
299
+ self.tag_names.append(tag.name)
300
+
301
+ # Update paths with the APIBlueprint's paths
302
+ url_prefix = options.get("url_prefix")
303
+ if url_prefix and api.url_prefix and url_prefix != api.url_prefix:
304
+ api.paths = {url_prefix + k.removeprefix(api.url_prefix): v for k, v in api.paths.items()}
305
+ api.url_prefix = url_prefix
306
+ elif url_prefix and not api.url_prefix:
307
+ api.paths = {url_prefix.rstrip("/") + "/" + k.lstrip("/"): v for k, v in api.paths.items()}
308
+ api.url_prefix = url_prefix
309
+ self.paths.update(**api.paths)
310
+
311
+ # Update component schemas with the APIBlueprint's component schemas
312
+ self.components_schemas.update(**api.components_schemas)
313
+
314
+ # Register the APIBlueprint with the current instance
315
+ self.register_blueprint(api, **options)
316
+
317
+ def register_api_view(
318
+ self, api_view: APIView, url_prefix: str | None = None, view_kwargs: dict[Any, Any] | None = None
319
+ ) -> None:
320
+ """
321
+ Register APIView
322
+
323
+ Args:
324
+ api_view: The APIView instance to register.
325
+ url_prefix: A path to prepend to all the APIView's urls
326
+ view_kwargs: Additional keyword arguments to pass to the API views.
327
+ """
328
+ if view_kwargs is None:
329
+ view_kwargs = {}
330
+
331
+ # Iterate through tags of the APIView
332
+ for tag in api_view.tags:
333
+ if tag.name not in self.tag_names:
334
+ # Append tag to the list of tags
335
+ self.tags.append(tag)
336
+
337
+ # Append tag name to the list of tag names
338
+ self.tag_names.append(tag.name)
339
+
340
+ # Update paths with the APIView's paths
341
+ if url_prefix and api_view.url_prefix and url_prefix != api_view.url_prefix:
342
+ api_view.paths = {url_prefix + k.removeprefix(api_view.url_prefix): v for k, v in api_view.paths.items()}
343
+ api_view.url_prefix = url_prefix
344
+ elif url_prefix and not api_view.url_prefix:
345
+ api_view.paths = {url_prefix.rstrip("/") + "/" + k.lstrip("/"): v for k, v in api_view.paths.items()}
346
+ api_view.url_prefix = url_prefix
347
+ self.paths.update(**api_view.paths)
348
+
349
+ # Update component schemas with the APIView's component schemas
350
+ self.components_schemas.update(**api_view.components_schemas)
351
+
352
+ # Register the APIView with the current instance
353
+ api_view.register(self, url_prefix=url_prefix, view_kwargs=view_kwargs)
354
+
355
+ def _add_url_rule(
356
+ self,
357
+ rule,
358
+ endpoint=None,
359
+ view_func=None,
360
+ provide_automatic_options=None,
361
+ **options,
362
+ ) -> None:
363
+ self.add_url_rule(rule, endpoint, view_func, provide_automatic_options, **options)
364
+
365
+ def _collect_openapi_info(
366
+ self,
367
+ rule: str,
368
+ func: Callable,
369
+ *,
370
+ tags: list[Tag] | None = None,
371
+ summary: str | None = None,
372
+ description: str | None = None,
373
+ external_docs: ExternalDocumentation | None = None,
374
+ operation_id: str | None = None,
375
+ responses: ResponseDict | None = None,
376
+ deprecated: bool | None = None,
377
+ security: list[dict[str, list[Any]]] | None = None,
378
+ servers: list[Server] | None = None,
379
+ openapi_extensions: dict[str, Any] | None = None,
380
+ doc_ui: bool = True,
381
+ method: str = HTTPMethod.GET,
382
+ ) -> ParametersTuple:
383
+ """
384
+ Collects OpenAPI specification information for Flask routes and view functions.
385
+
386
+ Args:
387
+ rule: Flask route.
388
+ func: Flask view_func.
389
+ tags: Adds metadata to a single tag.
390
+ summary: A short summary of what the operation does.
391
+ description: A verbose explanation of the operation behavior.
392
+ external_docs: Additional external documentation for this operation.
393
+ operation_id: Unique string used to identify the operation.
394
+ responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
395
+ deprecated: Declares this operation to be deprecated.
396
+ security: A declaration of which security mechanisms can be used for this operation.
397
+ servers: An alternative server array to service this operation.
398
+ openapi_extensions: Allows extensions to the OpenAPI Schema.
399
+ doc_ui: Declares this operation to be shown. Default to True.
400
+ method: HTTP method for the operation. Defaults to GET.
401
+ """
402
+ if doc_ui is True:
403
+ # Convert key to string
404
+ new_responses = convert_responses_key_to_string(responses or {})
405
+
406
+ # Global response: combine API responses
407
+ combine_responses = {**self.responses, **new_responses}
408
+
409
+ # Create operation
410
+ operation = get_operation(
411
+ func, summary=summary, description=description, openapi_extensions=openapi_extensions
412
+ )
413
+ # Set external docs
414
+ if external_docs:
415
+ operation.externalDocs = external_docs
416
+
417
+ # Unique string used to identify the operation.
418
+ operation.operationId = operation_id or self.operation_id_callback(
419
+ name=func.__name__, path=rule, method=method
420
+ )
421
+
422
+ # Only set `deprecated` if True, otherwise leave it as None
423
+ if deprecated is not None:
424
+ operation.deprecated = deprecated
425
+
426
+ # Add security
427
+ if security:
428
+ operation.security = security
429
+
430
+ # Add servers
431
+ if servers:
432
+ operation.servers = servers
433
+
434
+ # Store tags
435
+ parse_and_store_tags(tags or [], self.tags, self.tag_names, operation)
436
+
437
+ # Parse response
438
+ get_responses(combine_responses, self.components_schemas, operation)
439
+
440
+ # Convert a route parameter format from /pet/<petId> to /pet/{petId}
441
+ uri = re.sub(r"<([^<:]+:)?", "{", rule).replace(">", "}")
442
+
443
+ # Parse method
444
+ parse_method(uri, method, self.paths, operation)
445
+
446
+ # Parse parameters
447
+ return parse_parameters(func, components_schemas=self.components_schemas, operation=operation)
448
+ else:
449
+ return parse_parameters(func, doc_ui=False)
@@ -0,0 +1,17 @@
1
+ # -*- coding: utf-8 -*-
2
+ # @Author : llc
3
+ # @Time : 2024/4/23 14:31
4
+
5
+
6
+ class BasePlugin:
7
+ name = None
8
+ display_name = None
9
+
10
+ @classmethod
11
+ def register(cls, doc_url: str) -> None:
12
+ """
13
+ Register the plugin.
14
+
15
+ Args:
16
+ doc_url (str): The API doc url.
17
+ """
flask_openapi/py.typed ADDED
File without changes