Skip to content

Commit e3b928a

Browse files
committed
Improving Code Comments
1 parent b2910e4 commit e3b928a

File tree

7 files changed

+419
-218
lines changed

7 files changed

+419
-218
lines changed

flask_openapi3/blueprint.py

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -35,49 +35,63 @@ def __init__(
3535
3636
Arguments:
3737
name: The name of the blueprint. It Will be prepared to each endpoint name.
38-
import_name: The name of the blueprint package, usually
39-
``__name__``. This helps locate the ``root_path`` for the blueprint.
40-
abp_tags: APIBlueprint tags for every api
41-
abp_security: APIBlueprint security for every api
42-
abp_responses: API responses, should be BaseModel, dict or None.
43-
doc_ui: Add openapi document UI(swagger, rapidoc and redoc). Defaults to True.
38+
import_name: The name of the blueprint package, usually ``__name__``.
39+
This helps locate the ``root_path`` for the blueprint.
40+
abp_tags: APIBlueprint tags for every API.
41+
abp_security: APIBlueprint security for every API.
42+
abp_responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
43+
doc_ui: Enable OpenAPI document UI (Swagger UI, Redoc and Rapidoc). Defaults to True.
4444
operation_id_callback: Callback function for custom operation_id generation.
45-
Receives name (str), path (str) and method (str) parameters.
46-
Defaults to `get_operation_id_for_path` from utils
45+
Receives name (str), path (str) and method (str) parameters.
46+
Defaults to `get_operation_id_for_path` from utils
4747
**kwargs: Flask Blueprint kwargs
4848
"""
4949
super(APIBlueprint, self).__init__(name, import_name, **kwargs)
50+
51+
# Initialize instance variables
5052
self.paths: Dict = dict()
5153
self.components_schemas: Dict = dict()
5254
self.tags: List[Tag] = []
5355
self.tag_names: List[str] = []
5456

57+
# Set values from arguments or default values
5558
self.abp_tags = abp_tags or []
5659
self.abp_security = abp_security or []
5760
self.abp_responses = abp_responses or {}
5861
self.doc_ui = doc_ui
62+
63+
# Set the operation ID callback function
5964
self.operation_id_callback: Callable = operation_id_callback
6065

6166
def register_api(self, api: "APIBlueprint") -> None:
6267
"""Register a nested APIBlueprint"""
68+
69+
# Check if the APIBlueprint is being registered on itself
6370
if api is self:
6471
raise ValueError("Cannot register a api blueprint on itself")
6572

73+
# Merge tags from the nested APIBlueprint
6674
for tag in api.tags:
6775
if tag.name not in self.tag_names:
6876
self.tags.append(tag)
6977

78+
# Merge paths from the nested APIBlueprint
7079
for path_url, path_item in api.paths.items():
7180
trail_slash = path_url.endswith("/")
72-
# merge url_prefix and new api blueprint path url
81+
82+
# Merge url_prefix and new API blueprint path url
7383
uri = self.url_prefix.rstrip("/") + "/" + path_url.lstrip("/") if self.url_prefix else path_url
74-
# strip the right slash
84+
85+
# Strip the right slash
7586
if not trail_slash:
7687
uri = uri.rstrip("/")
88+
7789
self.paths[uri] = path_item
7890

91+
# Merge component schemas from the nested APIBlueprint
7992
self.components_schemas.update(**api.components_schemas)
8093

94+
# Register the nested APIBlueprint as a blueprint
8195
self.register_blueprint(api)
8296

8397
def _do_decorator(
@@ -102,7 +116,8 @@ def _do_decorator(
102116
method: str = HTTPMethod.GET
103117
) -> Tuple[Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel], Type[BaseModel]]:
104118
"""
105-
Collect openapi specification information
119+
Collects OpenAPI specification information for Flask routes and view functions.
120+
106121
Arguments:
107122
rule: Flask route
108123
func: Flask view_func
@@ -113,7 +128,7 @@ def _do_decorator(
113128
operation_id: Unique string used to identify the operation.
114129
extra_form: Extra information describing the request body(application/form).
115130
extra_body: Extra information describing the request body(application/json).
116-
responses: API responses, should be BaseModel, dict or None.
131+
responses: API responses should be either a subclass of BaseModel, a dictionary, or None.
117132
extra_responses: Extra information for responses.
118133
deprecated: Declares this operation to be deprecated.
119134
security: A declaration of which security mechanisms can be used for this operation.
@@ -126,54 +141,54 @@ def _do_decorator(
126141
responses = {}
127142
if extra_responses is None:
128143
extra_responses = {}
129-
# global response combine api responses
144+
# Global response: combine API responses
130145
combine_responses = deepcopy(self.abp_responses)
131146
combine_responses.update(**responses)
132-
# create operation
147+
# Create operation
133148
operation = get_operation(
134149
func,
135150
summary=summary,
136151
description=description,
137152
openapi_extensions=openapi_extensions
138153
)
139-
# set external docs
154+
# Set external docs
140155
operation.externalDocs = external_docs
141156
# Unique string used to identify the operation.
142157
operation.operationId = operation_id or self.operation_id_callback(
143158
name=func.__name__, path=rule, method=method
144159
)
145-
# only set `deprecated` if True otherwise leave it as None
160+
# Only set `deprecated` if True, otherwise leave it as None
146161
operation.deprecated = deprecated
147-
# add security
162+
# Add security
148163
if security is None:
149164
security = []
150165
operation.security = security + self.abp_security or None
151-
# add servers
166+
# Add servers
152167
operation.servers = servers
153-
# store tags
168+
# Store tags
154169
tags = tags + self.abp_tags if tags else self.abp_tags
155170
parse_and_store_tags(tags, self.tags, self.tag_names, operation)
156-
# parse parameters
171+
# Parse parameters
157172
header, cookie, path, query, form, body = parse_parameters(
158173
func,
159174
extra_form=extra_form,
160175
extra_body=extra_body,
161176
components_schemas=self.components_schemas,
162177
operation=operation
163178
)
164-
# parse response
179+
# Parse response
165180
get_responses(combine_responses, extra_responses, self.components_schemas, operation)
166-
# /pet/<petId> --> /pet/{petId}
181+
# Convert route parameter format from /pet/<petId> to /pet/{petId}
167182
uri = re.sub(r"<([^<:]+:)?", "{", rule).replace(">", "}")
168183
trail_slash = uri.endswith("/")
169-
# merge url_prefix and uri
184+
# Merge url_prefix and uri
170185
uri = self.url_prefix.rstrip("/") + "/" + uri.lstrip("/") if self.url_prefix else uri
171186
if not trail_slash:
172187
uri = uri.rstrip("/")
173-
# parse method
188+
# Parse method
174189
parse_method(uri, method, self.paths, operation)
175190
return header, cookie, path, query, form, body
176191
else:
177-
# parse parameters
192+
# Parse parameters
178193
header, cookie, path, query, form, body = parse_parameters(func, doc_ui=False)
179194
return header, cookie, path, query, form, body

flask_openapi3/commands.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,34 @@
1010
from .markdown import openapi_to_markdown
1111

1212

13-
@click.command(name='openapi')
14-
@click.option('--output', '-o', type=click.Path(), help='The output file path.')
15-
@click.option('--format', '-f', type=click.Choice(['json', 'yaml', 'markdown']), help='The output file format.')
16-
@click.option('--indent', '-i', type=int, help='The indentation for JSON dumps.')
17-
@click.option('--ensure_ascii', '-a', is_flag=True, help='Ensure ASCII characters or not. Defaults to False.')
13+
@click.command(name="openapi")
14+
@click.option("--output", "-o", type=click.Path(), help="The output file path.")
15+
@click.option("--format", "-f", type=click.Choice(["json", "yaml", "markdown"]), help="The output file format.")
16+
@click.option("--indent", "-i", type=int, help="The indentation for JSON dumps.")
17+
@click.option("--ensure_ascii", "-a", is_flag=True, help="Ensure ASCII characters or not. Defaults to False.")
1818
@with_appcontext
1919
def openapi_command(output, format, indent, ensure_ascii):
2020
"""Export the OpenAPI Specification to console or a file"""
21-
if hasattr(current_app, 'api_doc'):
21+
22+
# Check if the current app has an api_doc attribute
23+
if hasattr(current_app, "api_doc"):
2224
obj = current_app.api_doc
23-
if format == 'yaml':
25+
26+
# Generate the OpenAPI Specification based on the specified format
27+
if format == "yaml":
2428
try:
2529
import yaml # type: ignore
2630
except ImportError:
2731
raise ImportError("pyyaml must be installed.")
2832
openapi = yaml.safe_dump(obj, allow_unicode=True)
29-
elif format == 'markdown':
33+
elif format == "markdown":
3034
openapi = openapi_to_markdown(obj)
3135
else:
3236
openapi = json.dumps(obj, indent=indent, ensure_ascii=ensure_ascii)
37+
38+
# Save the OpenAPI Specification to a file if the output path is provided
3339
if output:
34-
with open(output, 'w', encoding='utf8') as f:
40+
with open(output, "w", encoding="utf8") as f:
3541
f.write(openapi)
3642
click.echo(f"Saved to {output}.")
3743
else:

0 commit comments

Comments
 (0)