-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathapp.py
More file actions
1830 lines (1557 loc) · 65.4 KB
/
app.py
File metadata and controls
1830 lines (1557 loc) · 65.4 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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import os
import signal
import sys
import warnings
from collections import defaultdict
from collections.abc import AsyncGenerator
from collections.abc import Awaitable
from collections.abc import Coroutine
from datetime import timedelta
from inspect import isasyncgen
from inspect import iscoroutinefunction as _inspect_iscoroutinefunction
from inspect import isgenerator
from types import TracebackType
from typing import Any
from typing import AnyStr
from typing import Callable
from typing import cast
from typing import NoReturn
from typing import Optional
from typing import overload
from typing import TypeVar
from urllib.parse import quote
from aiofiles import open as async_open
from aiofiles.base import AiofilesContextManager
from flask.sansio.app import App
from flask.sansio.scaffold import setupmethod
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from hypercorn.typing import ASGIReceiveCallable
from hypercorn.typing import ASGISendCallable
from hypercorn.typing import Scope
from werkzeug.datastructures import Authorization
from werkzeug.datastructures import Headers
from werkzeug.datastructures import ImmutableDict
from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import InternalServerError
from werkzeug.routing import BuildError
from werkzeug.routing import MapAdapter
from werkzeug.routing import RoutingException
from werkzeug.wrappers import Response as WerkzeugResponse
from .asgi import ASGIHTTPConnection
from .asgi import ASGILifespan
from .asgi import ASGIWebsocketConnection
from .cli import AppGroup
from .config import Config
from .ctx import _AppCtxGlobals
from .ctx import AppContext
from .ctx import has_request_context
from .ctx import has_websocket_context
from .ctx import RequestContext
from .ctx import WebsocketContext
from .globals import _cv_app
from .globals import _cv_request
from .globals import _cv_websocket
from .globals import g
from .globals import request
from .globals import request_ctx
from .globals import session
from .globals import websocket
from .globals import websocket_ctx
from .helpers import get_debug_flag
from .helpers import get_flashed_messages
from .helpers import send_from_directory
from .routing import QuartMap
from .routing import QuartRule
from .sessions import SecureCookieSessionInterface
from .signals import appcontext_tearing_down
from .signals import got_background_exception
from .signals import got_request_exception
from .signals import got_serving_exception
from .signals import got_websocket_exception
from .signals import request_finished
from .signals import request_started
from .signals import request_tearing_down
from .signals import websocket_finished
from .signals import websocket_started
from .signals import websocket_tearing_down
from .templating import _default_template_ctx_processor
from .templating import Environment
from .testing import make_test_body_with_headers
from .testing import make_test_headers_path_and_query_string
from .testing import make_test_scope
from .testing import no_op_push
from .testing import QuartClient
from .testing import QuartCliRunner
from .testing import sentinel
from .testing import TestApp
from .typing import AfterServingCallable
from .typing import AfterWebsocketCallable
from .typing import ASGIHTTPProtocol
from .typing import ASGILifespanProtocol
from .typing import ASGIWebsocketProtocol
from .typing import BeforeServingCallable
from .typing import BeforeWebsocketCallable
from .typing import Event
from .typing import FilePath
from .typing import HeadersValue
from .typing import ResponseReturnValue
from .typing import ResponseTypes
from .typing import ShellContextProcessorCallable
from .typing import StatusCode
from .typing import TeardownCallable
from .typing import TemplateFilterCallable
from .typing import TemplateGlobalCallable
from .typing import TemplateTestCallable
from .typing import TestAppProtocol
from .typing import TestClientProtocol
from .typing import WebsocketCallable
from .typing import WhileServingCallable
from .utils import cancel_tasks
from .utils import file_path_to_path
from .utils import MustReloadError
from .utils import observe_changes
from .utils import restart
from .utils import run_sync
from .wrappers import BaseRequestWebsocket
from .wrappers import Request
from .wrappers import Response
from .wrappers import Websocket
if sys.version_info >= (3, 10):
from typing import ParamSpec
else:
from typing_extensions import ParamSpec
# Python 3.14 deprecated asyncio.iscoroutinefunction, but suggested
# inspect.iscoroutinefunction does not work correctly in some Python
# versions before 3.12.
# See https://github.com/python/cpython/issues/122858#issuecomment-2466239748
if sys.version_info >= (3, 12):
iscoroutinefunction = _inspect_iscoroutinefunction
else:
iscoroutinefunction = asyncio.iscoroutinefunction
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
T_after_serving = TypeVar("T_after_serving", bound=AfterServingCallable)
T_after_websocket = TypeVar("T_after_websocket", bound=AfterWebsocketCallable)
T_before_serving = TypeVar("T_before_serving", bound=BeforeServingCallable)
T_before_websocket = TypeVar("T_before_websocket", bound=BeforeWebsocketCallable)
T_shell_context_processor = TypeVar(
"T_shell_context_processor", bound=ShellContextProcessorCallable
)
T_teardown = TypeVar("T_teardown", bound=TeardownCallable)
T_template_filter = TypeVar("T_template_filter", bound=TemplateFilterCallable)
T_template_global = TypeVar("T_template_global", bound=TemplateGlobalCallable)
T_template_test = TypeVar("T_template_test", bound=TemplateTestCallable)
T_websocket = TypeVar("T_websocket", bound=WebsocketCallable)
T_while_serving = TypeVar("T_while_serving", bound=WhileServingCallable)
T = TypeVar("T", bound=Any)
P = ParamSpec("P")
def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
if value is None or isinstance(value, timedelta):
return value
return timedelta(seconds=value)
class Quart(App):
"""The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
:meth:`~quart.app.Quart.handle_request`, from an application
viewpoint all the other methods are vital.
This can be extended in many ways, with most methods designed with
this in mind. Additionally any of the classes listed as attributes
can be replaced.
Attributes:
aborter_class: The class to use to raise HTTP error via the abort
helper function.
app_ctx_globals_class: The class to use for the ``g`` object
asgi_http_class: The class to use to handle the ASGI HTTP
protocol.
asgi_lifespan_class: The class to use to handle the ASGI
lifespan protocol.
asgi_websocket_class: The class to use to handle the ASGI
websocket protocol.
config_class: The class to use for the configuration.
env: The name of the environment the app is running on.
event_class: The class to use to signal an event in an async
manner.
debug: Wrapper around configuration DEBUG value, in many places
this will result in more output if True. If unset, debug
mode will be activated if environ is set to 'development'.
jinja_environment: The class to use for the jinja environment.
jinja_options: The default options to set when creating the jinja
environment.
permanent_session_lifetime: Wrapper around configuration
PERMANENT_SESSION_LIFETIME value. Specifies how long the session
data should survive.
request_class: The class to use for requests.
response_class: The class to user for responses.
secret_key: Warpper around configuration SECRET_KEY value. The app
secret for signing sessions.
session_interface: The class to use as the session interface.
shutdown_event: This event is set when the app starts to
shutdown allowing waiting tasks to know when to stop.
url_map_class: The class to map rules to endpoints.
url_rule_class: The class to use for URL rules.
websocket_class: The class to use for websockets.
"""
asgi_http_class: type[ASGIHTTPProtocol]
asgi_lifespan_class: type[ASGILifespanProtocol]
asgi_websocket_class: type[ASGIWebsocketProtocol]
shutdown_event: Event
test_app_class: type[TestAppProtocol]
test_client_class: type[TestClientProtocol] # type: ignore[assignment]
aborter_class = Aborter
app_ctx_globals_class = _AppCtxGlobals
asgi_http_class = ASGIHTTPConnection
asgi_lifespan_class = ASGILifespan
asgi_websocket_class = ASGIWebsocketConnection
config_class = Config
event_class = asyncio.Event
jinja_environment = Environment # type: ignore[assignment]
lock_class = asyncio.Lock
request_class = Request
response_class = Response
session_interface = SecureCookieSessionInterface()
test_app_class = TestApp
test_client_class = QuartClient # type: ignore[assignment]
test_cli_runner_class = QuartCliRunner # type: ignore
url_map_class = QuartMap
url_rule_class = QuartRule # type: ignore[assignment]
websocket_class = Websocket
default_config = ImmutableDict(
{
"APPLICATION_ROOT": "/",
"BACKGROUND_TASK_SHUTDOWN_TIMEOUT": 5, # Second
"BODY_TIMEOUT": 60, # Second
"DEBUG": None,
"ENV": None,
"EXPLAIN_TEMPLATE_LOADING": False,
"MAX_CONTENT_LENGTH": 16 * 1024 * 1024, # 16 MB Limit
"MAX_COOKIE_SIZE": 4093,
"MAX_FORM_MEMORY_SIZE": 500_000,
"MAX_FORM_PARTS": 1_000,
"PERMANENT_SESSION_LIFETIME": timedelta(days=31),
# Replaces PREFERRED_URL_SCHEME to allow for WebSocket scheme
"PREFER_SECURE_URLS": False,
"PRESERVE_CONTEXT_ON_EXCEPTION": None,
"PROPAGATE_EXCEPTIONS": None,
"PROVIDE_AUTOMATIC_OPTIONS": True,
"RESPONSE_TIMEOUT": 60, # Second
"SECRET_KEY": None,
"SECRET_KEY_FALLBACKS": None,
"SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),
"SERVER_NAME": None,
"SESSION_COOKIE_DOMAIN": None,
"SESSION_COOKIE_HTTPONLY": True,
"SESSION_COOKIE_NAME": "session",
"SESSION_COOKIE_PARTITIONED": False,
"SESSION_COOKIE_PATH": None,
"SESSION_COOKIE_SAMESITE": None,
"SESSION_COOKIE_SECURE": False,
"SESSION_REFRESH_EACH_REQUEST": True,
"TEMPLATES_AUTO_RELOAD": None,
"TESTING": False,
"TRAP_BAD_REQUEST_ERRORS": None,
"TRAP_HTTP_EXCEPTIONS": False,
}
)
def __init__(
self,
import_name: str,
static_url_path: str | None = None,
static_folder: str | None = "static",
static_host: str | None = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: str | None = "templates",
instance_path: str | None = None,
instance_relative_config: bool = False,
root_path: str | None = None,
) -> None:
"""Construct a Quart web application.
Use to create a new web application to which requests should
be handled, as specified by the various attached url
rules. See also :class:`~quart.static.PackageStatic` for
additional constructor arguments.
Arguments:
import_name: The name at import of the application, use
``__name__`` unless there is a specific issue.
host_matching: Optionally choose to match the host to the
configured host on request (404 if no match).
instance_path: Optional path to an instance folder, for
deployment specific settings and files.
instance_relative_config: If True load the config from a
path relative to the instance path.
Attributes:
after_request_funcs: The functions to execute after a
request has been handled.
after_websocket_funcs: The functions to execute after a
websocket has been handled.
before_request_funcs: The functions to execute before handling
a request.
before_websocket_funcs: The functions to execute before handling
a websocket.
"""
super().__init__(
import_name,
static_url_path,
static_folder,
static_host,
host_matching,
subdomain_matching,
template_folder,
instance_path,
instance_relative_config,
root_path,
)
self.after_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.after_websocket_funcs: dict[
AppOrBlueprintKey, list[AfterWebsocketCallable]
] = defaultdict(list)
self.background_tasks: set[asyncio.Task] = set()
self.before_serving_funcs: list[Callable[[], Awaitable[None]]] = []
self.before_websocket_funcs: dict[
AppOrBlueprintKey, list[BeforeWebsocketCallable]
] = defaultdict(list)
self.teardown_websocket_funcs: dict[
AppOrBlueprintKey, list[TeardownCallable]
] = defaultdict(list)
self.while_serving_gens: list[AsyncGenerator[None, None]] = []
self.template_context_processors[None] = [_default_template_ctx_processor]
self.cli = AppGroup()
self.cli.name = self.name
if self.has_static_folder:
assert bool(static_host) == host_matching, (
"Invalid static_host/host_matching combination"
)
self.add_url_rule(
f"{self.static_url_path}/<path:filename>",
"static",
self.send_static_file,
host=static_host,
)
def get_send_file_max_age(self, filename: str | None) -> int | None:
"""Used by :func:`send_file` to determine the ``max_age`` cache
value for a given file path if it wasn't passed.
By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
the configuration of :data:`~flask.current_app`. This defaults
to ``None``, which tells the browser to use conditional requests
instead of a timed cache, which is usually preferable.
Note this is a duplicate of the same method in the Quart
class.
"""
value = self.config["SEND_FILE_MAX_AGE_DEFAULT"]
if value is None:
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
return value
return None
async def send_static_file(self, filename: str) -> Response:
if not self.has_static_folder:
raise RuntimeError("No static folder for this object")
return await send_from_directory(self.static_folder, filename)
async def open_resource(
self,
path: FilePath,
mode: str = "rb",
) -> AiofilesContextManager:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_resource(path) as file_:
await file_.read()
"""
if mode not in {"r", "rb", "rt"}:
raise ValueError("Files can only be opened for reading")
return async_open(os.path.join(self.root_path, path), mode) # type: ignore
async def open_instance_resource(
self, path: FilePath, mode: str = "rb"
) -> AiofilesContextManager:
"""Open a file for reading.
Use as
.. code-block:: python
async with await app.open_instance_resource(path) as file_:
await file_.read()
"""
return async_open(self.instance_path / file_path_to_path(path), mode) # type: ignore
def create_jinja_environment(self) -> Environment: # type: ignore
"""Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
"""
options = dict(self.jinja_options)
if "autoescape" not in options:
options["autoescape"] = self.select_jinja_autoescape
if "auto_reload" not in options:
options["auto_reload"] = self.config["TEMPLATES_AUTO_RELOAD"]
jinja_env = self.jinja_environment(self, **options)
jinja_env.globals.update(
{
"config": self.config,
"g": g,
"get_flashed_messages": get_flashed_messages,
"request": request,
"session": session,
"url_for": self.url_for,
}
)
jinja_env.policies["json.dumps_function"] = self.json.dumps
return jinja_env
async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
names = [None]
if has_request_context():
names.extend(reversed(request_ctx.request.blueprints)) # type: ignore
elif has_websocket_context():
names.extend(reversed(websocket_ctx.websocket.blueprints)) # type: ignore
extra_context: dict[str, Any] = {}
for name in names:
for processor in self.template_context_processors[name]:
extra_context.update(await self.ensure_async(processor)()) # type: ignore[call-overload]
original = context.copy()
context.update(extra_context)
context.update(original)
@setupmethod
def before_serving(
self,
func: T_before_serving,
) -> T_before_serving:
"""Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_serving
async def func():
...
Arguments:
func: The function itself.
"""
self.before_serving_funcs.append(func)
return func
@setupmethod
def while_serving(
self,
func: T_while_serving,
) -> T_while_serving:
"""Add a while serving generator function.
This will allow the generator provided to be invoked at
startup and then again at shutdown.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.while_serving
async def func():
... # Startup
yield
... # Shutdown
Arguments:
func: The function itself.
"""
self.while_serving_gens.append(func())
return func
@setupmethod
def after_serving(
self,
func: T_after_serving,
) -> T_after_serving:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_serving
async def func():
...
Arguments:
func: The function itself.
"""
self.after_serving_funcs.append(func)
return func
def create_url_adapter(
self, request: BaseRequestWebsocket | None
) -> MapAdapter | None:
"""Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
"""
if request is not None:
subdomain = (
(self.url_map.default_subdomain or None)
if not self.subdomain_matching
else None
)
return self.url_map.bind_to_request( # type: ignore[attr-defined]
request, subdomain, self.config["SERVER_NAME"]
)
if self.config["SERVER_NAME"] is not None:
scheme = "https" if self.config["PREFER_SECURE_URLS"] else "http"
return self.url_map.bind(self.config["SERVER_NAME"], url_scheme=scheme)
return None
def websocket(
self,
rule: str,
**options: Any,
) -> Callable[[T_websocket], T_websocket]:
"""Add a websocket to the application.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.websocket('/')
async def websocket_route():
...
Arguments:
rule: The path to route on, should start with a ``/``.
endpoint: Optional endpoint name, if not present the
function name is used.
defaults: A dictionary of variables to provide automatically, use
to provide a simpler default path for a route, e.g. to allow
for ``/book`` rather than ``/book/0``,
.. code-block:: python
@app.websocket('/book', defaults={'page': 0})
@app.websocket('/book/<int:page>')
def book(page):
...
host: The full host name for this route (should include subdomain
if needed) - cannot be used with subdomain.
subdomain: A subdomain for this specific route.
strict_slashes: Strictly match the trailing slash present in the
path. Will redirect a leaf (no slash) to a branch (with slash).
"""
def decorator(func: T_websocket) -> T_websocket:
endpoint = options.pop("endpoint", None)
self.add_websocket(
rule,
endpoint,
func,
**options,
)
return func
return decorator
def add_websocket(
self,
rule: str,
endpoint: str | None = None,
view_func: WebsocketCallable | None = None,
**options: Any,
) -> None:
"""Add a websocket url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def websocket_route():
...
app.add_websocket('/', websocket_route)
Arguments:
rule: The path to route on, should start with a ``/``.
endpoint: Optional endpoint name, if not present the
function name is used.
view_func: Callable that returns a response.
defaults: A dictionary of variables to provide automatically, use
to provide a simpler default path for a route, e.g. to allow
for ``/book`` rather than ``/book/0``,
.. code-block:: python
@app.websocket('/book', defaults={'page': 0})
@app.websocket('/book/<int:page>')
def book(page):
...
host: The full host name for this route (should include subdomain
if needed) - cannot be used with subdomain.
subdomain: A subdomain for this specific route.
strict_slashes: Strictly match the trailing slash present in the
path. Will redirect a leaf (no slash) to a branch (with slash).
"""
return self.add_url_rule(
rule,
endpoint,
view_func,
methods={"GET"},
websocket=True,
**options,
)
def url_for(
self,
endpoint: str,
*,
_anchor: str | None = None,
_external: bool | None = None,
_method: str | None = None,
_scheme: str | None = None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
endpoint: The endpoint to build a url for, if prefixed with
``.`` it targets endpoint's in the current blueprint.
_anchor: Additional anchor text to append (i.e. #text).
_external: Return an absolute url for external (to app) usage.
_method: The method to consider alongside the endpoint.
_scheme: A specific scheme to use.
values: The values to build into the URL, as specified in
the endpoint rule.
"""
app_context = _cv_app.get(None)
request_context = _cv_request.get(None)
websocket_context = _cv_websocket.get(None)
if request_context is not None:
url_adapter = request_context.url_adapter
if endpoint.startswith("."):
if request.blueprint is not None:
endpoint = request.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = _scheme is not None
elif websocket_context is not None:
url_adapter = websocket_context.url_adapter
if endpoint.startswith("."):
if websocket.blueprint is not None:
endpoint = websocket.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = _scheme is not None
elif app_context is not None:
url_adapter = app_context.url_adapter
if _external is None:
_external = True
else:
url_adapter = self.create_url_adapter(None)
if _external is None:
_external = True
if url_adapter is None:
raise RuntimeError(
"Unable to create a url adapter, try setting the SERVER_NAME"
" config variable."
)
if _scheme is not None and not _external:
raise ValueError("External must be True for scheme usage")
self.inject_url_defaults(endpoint, values)
old_scheme = None
if _scheme is not None:
old_scheme = url_adapter.url_scheme
url_adapter.url_scheme = _scheme
try:
url = url_adapter.build(
endpoint, values, method=_method, force_external=_external
)
except BuildError as error:
return self.handle_url_build_error(error, endpoint, values)
finally:
if old_scheme is not None:
url_adapter.url_scheme = old_scheme
if _anchor is not None:
quoted_anchor = quote(_anchor, safe="%!#$&'()*+,/:;=?@")
url = f"{url}#{quoted_anchor}"
return url
def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {"app": self, "g": g}
for processor in self.shell_context_processors:
context.update(processor())
return context
def run(
self,
host: str | None = None,
port: int | None = None,
debug: bool | None = None,
use_reloader: bool = True,
loop: asyncio.AbstractEventLoop | None = None,
ca_certs: str | None = None,
certfile: str | None = None,
keyfile: str | None = None,
**kwargs: Any,
) -> None:
"""Run this application.
This is best used for development only, see Hypercorn for
production servers.
Arguments:
host: Hostname to listen on. By default this is loopback
only, use 0.0.0.0 to have the server listen externally.
port: Port number to listen on.
debug: If set enable (or disable) debug mode and debug output.
use_reloader: Automatically reload on code changes.
loop: Asyncio loop to create the server in, if None, take default one.
If specified it is the caller's responsibility to close and cleanup the
loop.
ca_certs: Path to the SSL CA certificate file.
certfile: Path to the SSL certificate file.
keyfile: Path to the SSL key file.
"""
if kwargs:
warnings.warn(
f"Additional arguments, {','.join(kwargs.keys())}, are not supported.\n"
"They may be supported by Hypercorn, which is the ASGI server Quart "
"uses by default. This method is meant for development and debugging.",
stacklevel=2,
)
if loop is None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if "QUART_DEBUG" in os.environ:
self.debug = get_debug_flag()
if debug is not None:
self.debug = debug
loop.set_debug(self.debug)
shutdown_event = asyncio.Event()
def _signal_handler(*_: Any) -> None:
shutdown_event.set()
for signal_name in {"SIGINT", "SIGTERM", "SIGBREAK"}:
if hasattr(signal, signal_name):
try:
loop.add_signal_handler(
getattr(signal, signal_name), _signal_handler
)
except NotImplementedError:
# Add signal handler may not be implemented on Windows
signal.signal(getattr(signal, signal_name), _signal_handler)
server_name = self.config.get("SERVER_NAME")
sn_host = None
sn_port = None
if server_name is not None:
sn_host, _, sn_port = server_name.partition(":")
if host is None:
host = sn_host or "127.0.0.1"
if port is None:
port = int(sn_port or "5000")
task = self.run_task(
host,
port,
debug,
ca_certs,
certfile,
keyfile,
shutdown_trigger=shutdown_event.wait, # type: ignore
)
print(f" * Serving Quart app '{self.name}'") # noqa: T201
print(f" * Debug mode: {self.debug or False}") # noqa: T201
print(" * Please use an ASGI server (e.g. Hypercorn) directly in production") # noqa: T201
scheme = "https" if certfile is not None and keyfile is not None else "http"
print(f" * Running on {scheme}://{host}:{port} (CTRL + C to quit)") # noqa: T201
tasks = [loop.create_task(task)]
if use_reloader:
tasks.append(
loop.create_task(observe_changes(asyncio.sleep, shutdown_event))
)
reload_ = False
try:
loop.run_until_complete(asyncio.gather(*tasks))
except MustReloadError:
reload_ = True
finally:
try:
_cancel_all_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
asyncio.set_event_loop(None)
loop.close()
if reload_:
restart()
def run_task(
self,
host: str = "127.0.0.1",
port: int = 5000,
debug: bool | None = None,
ca_certs: str | None = None,
certfile: str | None = None,
keyfile: str | None = None,
shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
) -> Coroutine[None, None, None]:
"""Return a task that when awaited runs this application.
This is best used for development only, see Hypercorn for
production servers.
Arguments:
host: Hostname to listen on. By default this is loopback
only, use 0.0.0.0 to have the server listen externally.
port: Port number to listen on.
debug: If set enable (or disable) debug mode and debug output.
ca_certs: Path to the SSL CA certificate file.
certfile: Path to the SSL certificate file.
keyfile: Path to the SSL key file.
"""
config = HyperConfig()
config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
config.accesslog = "-"
config.bind = [f"{host}:{port}"]
config.ca_certs = ca_certs
config.certfile = certfile
if debug is not None:
self.debug = debug
config.errorlog = config.accesslog
config.keyfile = keyfile
return serve(self, config, shutdown_trigger=shutdown_trigger)
def test_client(
self, use_cookies: bool = True, **kwargs: Any
) -> TestClientProtocol:
"""Creates and returns a test client."""
return self.test_client_class(self, use_cookies=use_cookies, **kwargs)
def test_cli_runner(self, **kwargs: Any) -> QuartCliRunner:
"""Creates and returns a CLI test runner."""
return self.test_cli_runner_class(self, **kwargs)
@setupmethod
def before_websocket(
self,
func: T_before_websocket,
) -> T_before_websocket:
"""Add a before websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.before_websocket
async def func():
...
Arguments:
func: The before websocket function itself.
"""
self.before_websocket_funcs[None].append(func)
return func
@setupmethod
def after_websocket(
self,
func: T_after_websocket,
) -> T_after_websocket:
"""Add an after websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python
@app.after_websocket
async def func(response):
return response
Arguments:
func: The after websocket function itself.
"""
self.after_websocket_funcs[None].append(func)
return func
@setupmethod
def teardown_websocket(
self,
func: T_teardown,
) -> T_teardown:
"""Add a teardown websocket function.
This is designed to be used as a decorator, if used to
decorate a synchronous function, the function will be wrapped
in :func:`~quart.utils.run_sync` and run in a thread executor
(with the wrapped function returned). An example usage,
.. code-block:: python