-
Notifications
You must be signed in to change notification settings - Fork 19
/
example.py
276 lines (229 loc) · 7.41 KB
/
example.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
An example integration with flask.
"""
import json
import sys
import transmute_core
import attr
from transmute_core import (
describe,
annotate,
default_context,
generate_swagger_html,
get_swagger_static_root,
ParamExtractor,
SwaggerSpec,
TransmuteFunction,
NoArgument,
)
from flask import Blueprint, Flask, Response, request
from schematics.models import Model
from schematics.types import StringType
from functools import wraps
SWAGGER_ATTR_NAME = "_tranmute_swagger"
STATIC_PATH = "/_swagger/static"
def transmute_route(app, fn, context=default_context):
"""
this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application.
"""
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
"""
the route being attached is a great place to start building up a
swagger spec. the SwaggerSpec object handles creating the
swagger spec from transmute routes for you.
almost all web frameworks provide some app-specific context
that one can add values to. It's recommended to attach
and retrieve the swagger spec from there.
"""
if not hasattr(app, SWAGGER_ATTR_NAME):
setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app.route(r, methods=transmute_func.methods)(handler)
def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
"""
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args, kwargs = ParamExtractorFlask().extract_params(
context, transmute_func, request.content_type
)
result = transmute_func(*args, **kwargs)
except Exception as e:
exc = e
"""
attaching the traceack is done for you in Python 3, but
in Python 2 the __traceback__ must be
attached to the object manually.
"""
exc.__traceback__ = sys.exc_info()[2]
"""
transmute_func.process_result handles converting
the response from the function into the response body,
the status code that should be returned, and the
response content-type.
"""
response = transmute_func.process_result(
context, result, exc, request.content_type
)
return Response(
response["body"],
status=response["code"],
mimetype=response["content-type"],
headers=response["headers"],
)
return (_convert_paths_to_flask(transmute_func.paths), handler)
def _convert_paths_to_flask(transmute_paths):
"""
convert transmute-core's path syntax (which uses {var} as the
variable wildcard) into flask's <var>.
"""
paths = []
for p in transmute_paths:
paths.append(p.replace("{", "<").replace("}", ">"))
return paths
class ParamExtractorFlask(ParamExtractor):
"""
The code that converts http parameters into function signature
arguments is complex, so the abstract class ParamExtractor is
provided as a convenience.
override the methods to complete the class.
"""
def __init__(self, *args, **kwargs):
"""
in the case of flask, this is blank. But it's common
to pass request-specific variables in the ParamExtractor,
to be used in the methods.
"""
super(ParamExtractorFlask, self).__init__(*args, **kwargs)
def _get_framework_args(self):
"""
this method should return back a dictionary of the values that
are normally passed into the handler (e.g. the "request" object
in aiohttp).
in the case of flask, this is blank.
"""
return {}
@property
def body(self):
return request.get_data()
@staticmethod
def _query_argument(key, is_list):
if key not in request.args:
return NoArgument
if is_list:
return request.args.getlist(key)
else:
return request.args[key]
@staticmethod
def _header_argument(key):
return request.headers.get(key, NoArgument)
@staticmethod
def _path_argument(key):
return request.match_info.get(key, NoArgument)
def add_swagger(app, json_route, html_route, **kwargs):
"""
add a swagger html page, and a swagger.json generated
from the routes added to the app.
"""
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = json.dumps(spec).encode("UTF-8")
@app.route(json_route)
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can be requested at swagger.io
headers={"Access-Control-Allow-Origin": "*"},
content_type="application/json",
)
# add the statics
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(STATIC_PATH, json_route).encode("utf-8")
@app.route(html_route)
def swagger_ui():
return Response(swagger_body, content_type="text/html")
# the blueprint work is the easiest way to integrate a static
# directory into flask.
blueprint = Blueprint(
"swagger", __name__, static_url_path=STATIC_PATH, static_folder=static_root
)
app.register_blueprint(blueprint)
# example usage.
@describe(
paths="/api/v1/multiply/{document_id}",
header_parameters=["header"],
body_parameters="foo",
)
@annotate(
{
"left": int,
"right": int,
"header": int,
"foo": str,
"return": int,
"document_id": str,
}
)
def multiply(left, right, foo, document_id, header=0):
return left * right
@describe(paths="/api/v1/multiply_body", body_parameters="body")
@annotate({"body": int})
def multiply_body(body):
return left * right
@describe(paths="/api/v1/test")
@annotate({"vals": [int], "return": [int]})
def foo(vals):
return vals
class SchematicsBody(Model):
name = StringType(max_length=5)
@describe(
paths="/api/v1/schematics", methods=["POST"], tags=["foo"], body_parameters="body"
)
@annotate({"body": SchematicsBody})
def schematics_example(body):
return None
@describe(
paths="/api/v1/header",
response_types={
200: {
"type": str,
"description": "success",
"headers": {
"location": {"description": "url to the location", "type": str}
},
},
},
)
def header():
return transmute_core.Response("foo", headers={"x-nothing": "value"})
@attr.s
class AttrsExample(object):
foo = attr.ib(type=str)
@describe(paths="/api/v1/attrs")
@annotate({"return": AttrsExample})
def attrs():
return AttrsExample(foo="bar")
app = Flask(__name__)
app = Flask(__name__)
transmute_route(app, attrs)
transmute_route(app, multiply)
transmute_route(app, multiply_body)
transmute_route(app, schematics_example)
transmute_route(app, foo)
transmute_route(app, header)
add_swagger(app, "/api/swagger.json", "/api/")
if __name__ == "__main__":
app.run(debug=True)