-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathextension.py
More file actions
478 lines (384 loc) · 15 KB
/
Copy pathextension.py
File metadata and controls
478 lines (384 loc) · 15 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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
from __future__ import annotations
import re
from collections.abc import Callable, Iterable
from functools import wraps
from types import new_class
from typing import Any, Literal, TypeVar
import click
from quart import Blueprint, current_app, Quart, render_template_string, ResponseReturnValue
from quart.cli import pass_script_info, ScriptInfo
from quart.json.provider import DefaultJSONProvider
from quart.typing import ResponseReturnValue as QuartResponseReturnValue
from .conversion import convert_response_return_value
from .mixins import TestClientMixin, WebsocketMixin
from .openapi import (
APIKeySecurityScheme,
ExternalDocumentation,
HttpSecurityScheme,
Info,
OAuth2SecurityScheme,
OpenAPIProvider,
OpenIdSecurityScheme,
QUART_SCHEMA_DEPRECATED_ATTRIBUTE,
QUART_SCHEMA_HIDDEN_ATTRIBUTE,
QUART_SCHEMA_OPERATION_ID_ATTRIBUTE,
QUART_SCHEMA_SECURITY_ATTRIBUTE,
QUART_SCHEMA_TAG_ATTRIBUTE,
SecuritySchemeBase,
Server,
Tag,
)
from .typing import PydanticDumpOptions
try:
from pydantic_core import to_jsonable_python
except ImportError:
to_jsonable_python = None
try:
from msgspec import to_builtins
except ImportError:
to_builtins = None
T = TypeVar("T", bound=Callable)
SecurityScheme = (
APIKeySecurityScheme
| HttpSecurityScheme
| OAuth2SecurityScheme
| OpenIdSecurityScheme
| SecuritySchemeBase
)
SecuritySchemeInput = (
APIKeySecurityScheme
| HttpSecurityScheme
| OAuth2SecurityScheme
| OpenIdSecurityScheme
| SecuritySchemeBase
| dict
)
PATH_RE = re.compile("<(?:[^:]*:)?([^>]+)>")
REDOC_TEMPLATE = """
<head>
<title>{{ title }}</title>
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<redoc spec-url="{{ url_for('openapi') }}"></redoc>
<script src="{{ redoc_js_url }}"></script>
<noscript>This page requires Javascript to function.</noscript>
</body>
"""
SCALAR_TEMPLATE = """
<head>
<title>{{ title }}</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script id="api-reference" data-url="{{ url_for('openapi') }}"></script>
<script src="{{ scalar_js_url }}"></script>
</body>
"""
SWAGGER_TEMPLATE = """
<head>
<link type="text/css" rel="stylesheet" href="{{ swagger_css_url }}">
<title>{{ title }}</title>
</head>
<body>
<div id="swagger-ui"></div>
<script src="{{ swagger_js_url }}"></script>
<script>
const ui = SwaggerUIBundle({
deepLinking: true,
dom_id: "#swagger-ui",
layout: "BaseLayout",
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
showExtensions: true,
showCommonExtensions: true,
url: "{{ url_for('openapi') }}"
});
</script>
</body>
"""
def create_json_provider(app: Quart) -> DefaultJSONProvider:
preference = app.config["QUART_SCHEMA_CONVERSION_PREFERENCE"]
class JSONProvider(DefaultJSONProvider):
@staticmethod
def default(object_: Any) -> Any:
try:
return super().default(object_)
except TypeError:
if to_jsonable_python is not None and preference != "msgspec":
return to_jsonable_python(object_)
elif to_builtins is not None and preference != "pydantic":
return to_builtins(object_)
else:
raise
return JSONProvider(app)
def hide(func: T) -> T:
"""Mark the func as hidden.
This will prevent the route from being included in the
autogenerated documentation.
"""
setattr(func, QUART_SCHEMA_HIDDEN_ATTRIBUTE, True)
return func
class QuartSchema:
"""A Quart-Schema instance.
This can be used to initialise Quart-Schema documentation a given
app, either directly,
.. code-block:: python
app = Quart(__name__)
QuartSchema(app)
or via the factory pattern,
.. code-block:: python
quart_schema = QuartSchema()
def create_app():
app = Quart(__name__)
quart_schema.init_app(app)
return app
This can be customised using the following arguments,
Arguments:
openapi_path: The path used to serve the openapi json on, or None
to disable documentation.
redoc_ui_path: The path used to serve the documentation UI using
redoc or None to disable redoc documentation.
scalar_ui_path: The path used to serve the documentation UI using
scalar or None to disable scalar documentation.
swagger_ui_path: The path used to serve the documentation UI using
swagger or None to disable swagger documentation.
info: A OpenAPI Info object describing the API.
tags: Specify the possible tags.
convert_casing: If true casing will be converted in JSON.
servers: Specify the server information.
security_schemes: The security schemes to be configured for this app.
security: The security schemes to apply globally (to all routes).
external_docs: External documentation information.
"""
openapi_provider_class: type[OpenAPIProvider] = OpenAPIProvider
def __init__(
self,
app: Quart | None = None,
*,
openapi_path: str | None = "/openapi.json",
redoc_ui_path: str | None = "/redocs",
scalar_ui_path: str | None = "/scalar",
swagger_ui_path: str | None = "/docs",
info: Info | dict | None = None,
tags: list[Tag | dict] | None = None,
convert_casing: bool = False,
servers: list[Server | dict] | None = None,
security_schemes: dict[str, SecuritySchemeInput] | None = None,
security: list[dict[str, list[str]]] | None = None,
external_docs: ExternalDocumentation | dict | None = None,
conversion_preference: Literal["msgspec", "pydantic", None] = None,
pydantic_dump_options: PydanticDumpOptions | None = None,
openapi_provider_class: type[OpenAPIProvider] | None = None,
) -> None:
self.openapi_path = openapi_path
self.redoc_ui_path = redoc_ui_path
self.scalar_ui_path = scalar_ui_path
self.swagger_ui_path = swagger_ui_path
self.convert_casing = convert_casing
self.conversion_preference = conversion_preference
self.pydantic_dump_options = {} if pydantic_dump_options is None else pydantic_dump_options
if openapi_provider_class is not None:
self.openapi_provider_class = openapi_provider_class
self.info: Info | None = None
if info is not None:
self.info = info if isinstance(info, Info) else Info(**info)
self.tags: list[Tag] | None = None
if tags is not None:
self.tags = [tag if isinstance(tag, Tag) else Tag(**tag) for tag in tags]
self.servers: list[Server] | None = None
if servers is not None:
self.servers = [
server if isinstance(server, Server) else Server(**server) for server in servers
]
self.security_schemes: dict[str, SecurityScheme] | None = None
if security_schemes is not None:
self.security_schemes = {}
for key, value in security_schemes.items():
if isinstance(value, dict):
if value["type"] == "apiKey":
self.security_schemes[key] = APIKeySecurityScheme(**value)
elif value["type"] == "http":
self.security_schemes[key] = HttpSecurityScheme(**value)
elif value["type"] == "oauth2":
self.security_schemes[key] = OAuth2SecurityScheme(**value)
elif value["type"] == "openIdConnect":
self.security_schemes[key] = OpenIdSecurityScheme(**value)
else:
self.security_schemes[key] = SecuritySchemeBase(**value)
else:
self.security_schemes[key] = value
self.security = security
self.external_docs: ExternalDocumentation | None = None
if external_docs is not None:
self.external_docs = (
external_docs
if isinstance(external_docs, ExternalDocumentation)
else ExternalDocumentation(**external_docs)
)
if app is not None:
self.init_app(app)
def init_app(self, app: Quart) -> None:
app.extensions["QUART_SCHEMA"] = self
if self.info is None:
self.info = Info(title=app.name, version="0.1.0")
app.test_client_class = new_class("TestClient", (TestClientMixin, app.test_client_class))
app.websocket_class = new_class( # type: ignore
"Websocket", (WebsocketMixin, app.websocket_class)
)
app.make_response = wrap_make_response(app.make_response) # type: ignore
app.config.setdefault(
"QUART_SCHEMA_SWAGGER_JS_URL",
"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.4.2/swagger-ui-bundle.js",
)
app.config.setdefault(
"QUART_SCHEMA_SWAGGER_CSS_URL",
"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.4.2/swagger-ui.min.css",
)
app.config.setdefault(
"QUART_SCHEMA_REDOC_JS_URL",
"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
)
app.config.setdefault(
"QUART_SCHEMA_SCALAR_JS_URL",
"https://cdn.jsdelivr.net/npm/@scalar/api-reference",
)
app.config.setdefault("QUART_SCHEMA_PYDANTIC_DUMP_OPTIONS", self.pydantic_dump_options)
app.config.setdefault("QUART_SCHEMA_CONVERT_CASING", self.convert_casing)
app.config.setdefault("QUART_SCHEMA_CONVERSION_PREFERENCE", self.conversion_preference)
app.json = create_json_provider(app)
self.openapi_provider = self.openapi_provider_class(app, self)
if self.openapi_path is not None:
hide(app.send_static_file.__func__) # type: ignore
app.add_url_rule(self.openapi_path, "openapi", self.openapi)
if self.redoc_ui_path is not None:
app.add_url_rule(self.redoc_ui_path, "redoc_ui", self.redoc_ui)
if self.scalar_ui_path is not None:
app.add_url_rule(self.scalar_ui_path, "scalar_ui", self.scalar_ui)
if self.swagger_ui_path is not None:
app.add_url_rule(self.swagger_ui_path, "swagger_ui", self.swagger_ui)
app.cli.add_command(_schema_command)
@hide
async def openapi(self) -> ResponseReturnValue:
schema = self.openapi_provider.schema()
return current_app.json.response(schema) # type: ignore
@hide
async def swagger_ui(self) -> str:
return await render_template_string(
SWAGGER_TEMPLATE,
title=self.info.title,
openapi_path=self.openapi_path,
swagger_js_url=current_app.config["QUART_SCHEMA_SWAGGER_JS_URL"],
swagger_css_url=current_app.config["QUART_SCHEMA_SWAGGER_CSS_URL"],
)
@hide
async def redoc_ui(self) -> str:
return await render_template_string(
REDOC_TEMPLATE,
title=self.info.title,
openapi_path=self.openapi_path,
redoc_js_url=current_app.config["QUART_SCHEMA_REDOC_JS_URL"],
)
@hide
async def scalar_ui(self) -> str:
return await render_template_string(
SCALAR_TEMPLATE,
title=self.info.title,
openapi_path=self.openapi_path,
scalar_js_url=current_app.config["QUART_SCHEMA_SCALAR_JS_URL"],
)
@click.command("schema")
@click.option(
"--output",
"-o",
type=click.Path(),
help="Output the spec to a file given by a path.",
)
@pass_script_info
def _schema_command(info: ScriptInfo, output: str | None) -> None:
app = info.load_app()
schema = app.extensions["QUART_SCHEMA"].openapi_provider.schema()
formatted_spec = app.json.dumps(schema, indent=2)
if output is not None:
with open(output, "w") as file_:
click.echo(formatted_spec, file=file_)
else:
click.echo(formatted_spec)
def wrap_make_response(func: Callable) -> Callable:
@wraps(func)
async def decorator(result: ResponseReturnValue) -> QuartResponseReturnValue:
return await func(convert_response_return_value(result))
return decorator
def operation_id(operationid: str) -> Callable[[T], T]:
"""Override the operationId of the route.
This allows for overriding the operationId, which is normally calculated from the
function name. The HTTP method will still be prepended to the overridden name.
Arguments:
operationid: The operation ID to associate.
"""
def decorator(func: T) -> T:
setattr(func, QUART_SCHEMA_OPERATION_ID_ATTRIBUTE, str(operationid))
return func
return decorator
def tag(tags: Iterable[str]) -> Callable[[T], T]:
"""Add tag names to the route.
This allows for tags to be associated with the route, thereby
allowing control over which routes are shown in the documentation.
Arguments:
tags: A List (or iterable) of tags to associate.
"""
def decorator(func: T) -> T:
setattr(func, QUART_SCHEMA_TAG_ATTRIBUTE, set(tags))
return func
return decorator
def tag_blueprint(blueprint: Blueprint, tags: Iterable[str]) -> None:
"""Add tag name to all endpoints in the blueprint.
This allows for tags to be associated with the blueprint, thereby
allowing control over which routes are shown in the documentation.
Arguments:
blueprint: The blueprint to affect.
tags: A List (or iterable) of tags to associate.
"""
setattr(blueprint, QUART_SCHEMA_TAG_ATTRIBUTE, set(tags))
def deprecate(func: T) -> T:
"""Mark endpoint as deprecated."""
setattr(func, QUART_SCHEMA_DEPRECATED_ATTRIBUTE, True)
return func
def deprecate_blueprint(blueprint: Blueprint) -> None:
"""Mark all endpoints in the blueprint as deprecated."""
setattr(blueprint, QUART_SCHEMA_DEPRECATED_ATTRIBUTE, True)
def security_scheme(schemes: Iterable[dict[str, list[str]]]) -> Callable[[T], T]:
"""Add security schemes to the route.
Allows security schemes to be associated with this route. Security
schemes first need to be defined on the constructor and can be
referenced here by name.
Arguments:
schemes: A List (or iterable) of security schemes to associate.
"""
def decorator(func: T) -> T:
setattr(func, QUART_SCHEMA_SECURITY_ATTRIBUTE, schemes)
return func
return decorator
def security_scheme_blueprint(
blueprint: Blueprint, schemes: Iterable[dict[str, list[str]]]
) -> None:
"""Add security schemes to the endpoints in the blueprint.
Allows security schemes to be associated with this
blueprint. Security schemes first need to be defined on the
constructor and can be referenced here by name.
Arguments:
blueprint: The blueprint to affect.
schemes: A List (or iterable) of security schemes to associate.
"""
setattr(blueprint, QUART_SCHEMA_SECURITY_ATTRIBUTE, schemes)