-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathextension.py
166 lines (137 loc) · 5.65 KB
/
extension.py
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
# -*- coding: utf-8 -*-
import flask
import functools
import types
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec import ResourceMeta
from flask_apispec.apidoc import ViewConverter, ResourceConverter
class FlaskApiSpec(object):
"""Flask-apispec extension.
Usage:
.. code-block:: python
app = Flask(__name__)
app.config.update({
'APISPEC_SPEC': APISpec(
title='pets',
version='v1',
openapi_version='2.0',
plugins=[MarshmallowPlugin()],
),
'APISPEC_SWAGGER_URL': '/swagger/',
})
docs = FlaskApiSpec(app)
@app.route('/pet/<pet_id>')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
docs.register(get_pet)
:param Flask app: App associated with API documentation
:param String static_folder: Static files folder location
:param String template_folder: Template files folder location
:param String static_url_path: URL to serve static files
:param APISpec spec: apispec specification associated with API documentation
"""
def __init__(self, app=None,
static_folder='./static',
template_folder='./templates',
static_url_path='/flask-apispec/static'):
self._deferred = []
self.app = app
self.view_converter = None
self.resource_converter = None
self.spec = None
self.static_folder = static_folder
self.template_folder = template_folder
self.static_url_path = static_url_path
if app:
self.init_app(app)
def init_app(self, app):
self.app = app
self.spec = self.app.config.get('APISPEC_SPEC') or \
make_apispec(self.app.config.get('APISPEC_TITLE', 'flask-apispec'),
self.app.config.get('APISPEC_VERSION', 'v1'),
self.app.config.get('APISPEC_OAS_VERSION', '2.0'))
self.add_swagger_routes()
self.resource_converter = ResourceConverter(self.app, spec=self.spec)
self.view_converter = ViewConverter(app=self.app, spec=self.spec)
for deferred in self._deferred:
deferred()
def _defer(self, callable, *args, **kwargs):
bound = functools.partial(callable, *args, **kwargs)
self._deferred.append(bound)
if self.app:
bound()
def add_swagger_routes(self):
blueprint = flask.Blueprint(
'flask-apispec',
__name__,
static_folder=self.static_folder,
template_folder=self.template_folder,
static_url_path=self.static_url_path,
)
json_url = self.app.config.get('APISPEC_SWAGGER_URL', '/swagger/')
if json_url:
blueprint.add_url_rule(json_url, 'swagger-json', self.swagger_json)
ui_url = self.app.config.get('APISPEC_SWAGGER_UI_URL', '/swagger-ui/')
if ui_url:
blueprint.add_url_rule(ui_url, 'swagger-ui', self.swagger_ui)
self.app.register_blueprint(blueprint)
def swagger_json(self):
return flask.jsonify(self.spec.to_dict())
def swagger_ui(self):
return flask.render_template('swagger-ui.html')
def register_existing_resources(self):
for name, rule in self.app.view_functions.items():
try:
blueprint_name, _ = name.split('.')
except ValueError:
blueprint_name = None
try:
self.register(rule, blueprint=blueprint_name)
except TypeError:
pass
def register(self, target, endpoint=None, blueprint=None,
resource_class_args=None, resource_class_kwargs=None):
"""Register a view.
:param target: view function or view class.
:param endpoint: (optional) endpoint name.
:param blueprint: (optional) blueprint name.
:param tuple resource_class_args: (optional) args to be forwarded to the
view class constructor.
:param dict resource_class_kwargs: (optional) kwargs to be forwarded to
the view class constructor.
"""
self._defer(self._register, target, endpoint, blueprint,
resource_class_args, resource_class_kwargs)
def _register(self, target, endpoint=None, blueprint=None,
resource_class_args=None, resource_class_kwargs=None):
"""Register a view.
:param target: view function or view class.
:param endpoint: (optional) endpoint name.
:param blueprint: (optional) blueprint name.
:param tuple resource_class_args: (optional) args to be forwarded to the
view class constructor.
:param dict resource_class_kwargs: (optional) kwargs to be forwarded to
the view class constructor.
"""
if isinstance(target, types.FunctionType):
paths = self.view_converter.convert(target, endpoint, blueprint)
elif isinstance(target, ResourceMeta):
paths = self.resource_converter.convert(
target,
endpoint,
blueprint,
resource_class_args=resource_class_args,
resource_class_kwargs=resource_class_kwargs,
)
else:
raise TypeError()
for path in paths:
self.spec.path(**path)
def make_apispec(title='flask-apispec', version='v1', openapi_version='2.0'):
return APISpec(
title=title,
version=version,
openapi_version=openapi_version,
plugins=[MarshmallowPlugin()],
)