-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathflask.py
More file actions
169 lines (134 loc) · 4.99 KB
/
flask.py
File metadata and controls
169 lines (134 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""Flask plugin. Includes a path helper that allows you to pass a view
function to `path`. Inspects URL rules and view docstrings.
Passing a view function::
from flask import Flask
app = Flask(__name__)
@app.route("/gists/<gist_id>")
def gist_detail(gist_id):
'''Gist detail view.
---
x-extension: metadata
get:
responses:
200:
schema:
$ref: '#/definitions/Gist'
'''
return "detail for gist {}".format(gist_id)
with app.test_request_context():
spec.path(view=gist_detail)
print(spec.to_dict()["paths"])
# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},
# 'x-extension': 'metadata'}}
Passing a method view function::
from flask import Flask
from flask.views import MethodView
app = Flask(__name__)
class GistApi(MethodView):
'''Gist API.
---
x-extension: metadata
'''
def get(self):
'''Gist view
---
responses:
200:
schema:
$ref: '#/definitions/Gist'
'''
pass
def post(self):
pass
method_view = GistApi.as_view("gists")
app.add_url_rule("/gists", view_func=method_view)
with app.test_request_context():
spec.path(view=method_view)
# Alternatively, pass in an app object as a kwarg
# spec.path(view=method_view, app=app)
print(spec.to_dict()["paths"])
# {'/gists': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},
# 'post': {},
# 'x-extension': 'metadata'}}
""" # noqa: E501
import re
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
from apispec import BasePlugin, yaml_utils
from apispec.exceptions import APISpecError
from flask import Flask, current_app
from flask.views import MethodView
from werkzeug.routing import Rule
if TYPE_CHECKING:
from flask.typing import RouteCallable
# from flask-restplus
RE_URL = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
class FlaskPlugin(BasePlugin):
"""APISpec plugin for Flask"""
@staticmethod
def flaskpath2openapi(path: str) -> str:
"""Convert a Flask URL rule to an OpenAPI-compliant path.
:param str path: Flask path template.
"""
return RE_URL.sub(r"{\1}", path)
@staticmethod
def _rule_for_view(
view: Union[Callable[..., Any], "RouteCallable"],
app: Optional[Flask] = None,
) -> Rule:
if app is None:
app = current_app
view_funcs = app.view_functions
endpoint = None
for ept, view_func in view_funcs.items():
if view_func == view:
endpoint = ept
if not endpoint:
raise APISpecError(f"Could not find endpoint for view {view}")
# WARNING: Assume 1 rule per view function for now
rule = app.url_map._rules_by_endpoint[endpoint][0]
return rule
@staticmethod
def _view_for_rule(
rule: Rule,
app: Optional[Flask] = None,
) -> Union[Callable[..., Any], "RouteCallable"]:
if app is None:
app = current_app
return app.view_functions[rule.endpoint]
def path_helper(
self,
path: Optional[str] = None,
operations: Optional[dict] = None,
parameters: Optional[List[dict]] = None,
*,
view: Optional[Union[Callable[..., Any], "RouteCallable"]] = None,
rule: Optional[Rule] = None,
app: Optional[Flask] = None,
**kwargs: Any,
) -> Optional[str]:
"""Path helper that allows passing a Flask view function."""
assert operations is not None
if rule is None:
assert view is not None
rule = self._rule_for_view(view, app=app)
if view is None:
view = self._view_for_rule(rule, app=app)
view_doc = view.__doc__ or ""
doc_operations = yaml_utils.load_operations_from_docstring(view_doc)
doc_operations = {
k: v
for k, v in doc_operations.items()
if rule.methods is None or k.upper() in rule.methods or k.startswith("x-")
}
operations.update(doc_operations)
if hasattr(view, "view_class") and issubclass(view.view_class, MethodView): # noqa: E501
# method attribute is dynamically added, which is supported by mypy
for method in view.methods: # type:ignore[union-attr]
if rule.methods and method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
method_docstring = method.__doc__ or ""
operations[method_name] = yaml_utils.load_yaml_from_docstring( # noqa: E501
method_docstring
)
return self.flaskpath2openapi(rule.rule)