-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathflask.py
More file actions
190 lines (154 loc) · 6.28 KB
/
flask.py
File metadata and controls
190 lines (154 loc) · 6.28 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# -*- coding: utf-8 -*-
"""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)
print(spec.to_dict()['paths'])
# {'/gists': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},
# 'post': {},
# 'x-extension': 'metadata'}}
Using DocumentedBlueprint:
from flask import Flask
from flask.views import MethodView
app = Flask(__name__)
documented_blueprint = DocumentedBlueprint('gistapi', __name__)
@documented_blueprint.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)
@documented_blueprint.route('/repos/<repo_id>', documented=False)
def repo_detail(repo_id):
'''This endpoint won't be documented
---
x-extension: metadata
get:
responses:
200:
schema:
$ref: '#/definitions/Repo'
'''
return 'detail for repo {}'.format(repo_id)
app.register_blueprint(documented_blueprint)
print(spec.to_dict()['paths'])
# {'/gists/{gist_id}': {'get': {'responses': {200: {'schema': {'$ref': '#/definitions/Gist'}}}},
# 'x-extension': 'metadata'}}
"""
from __future__ import absolute_import
from collections import defaultdict
import re
from flask import current_app, Blueprint
from flask.views import MethodView
from apispec.compat import iteritems
from apispec import BasePlugin, yaml_utils
from apispec.exceptions import APISpecError
# from flask-restplus
RE_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
class FlaskPlugin(BasePlugin):
"""APISpec plugin for Flask"""
@staticmethod
def flaskpath2openapi(path):
"""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):
view_funcs = current_app.view_functions
endpoint = None
for ept, view_func in iteritems(view_funcs):
if view_func == view:
endpoint = ept
if not endpoint:
raise APISpecError('Could not find endpoint for view {0}'.format(view))
# WARNING: Assume 1 rule per view function for now
rule = current_app.url_map._rules_by_endpoint[endpoint][0]
return rule
def path_helper(self, operations, view, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView):
for method in view.methods:
if method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)
return self.flaskpath2openapi(rule.rule)
class DocumentedBlueprint(Blueprint):
"""Flask Blueprint which documents every view function defined in it."""
def __init__(self, name, import_name, spec):
"""
Initialize blueprint. Must be provided an APISpec object.
:param APISpec spec: APISpec object which will be attached to the blueprint.
"""
super(DocumentedBlueprint, self).__init__(name, import_name)
self.documented_view_functions = defaultdict(list)
self.spec = spec
def route(self, rule, documented=True, **options):
"""If documented is set to True, the route will be added to the spec.
:param bool documented: Whether you want this route to be added to the spec or not.
"""
return super(DocumentedBlueprint, self).route(rule, documented=documented, **options)
def add_url_rule(self, rule, endpoint=None, view_func=None, documented=True, **options):
"""If documented is set to True, the route will be added to the spec.
:param bool documented: Whether you want this route to be added to the spec or not.
"""
super(DocumentedBlueprint, self).add_url_rule(rule, endpoint=endpoint, view_func=view_func, **options)
if documented:
self.documented_view_functions[rule].append(view_func)
def register(self, app, options, first_registration=False):
"""Register current blueprint in the app. Add all the view_functions to the spec."""
super(DocumentedBlueprint, self).register(app, options, first_registration=first_registration)
with app.app_context():
for rule, view_functions in self.documented_view_functions.items():
[self.spec.path(view=f) for f in view_functions]