prefect-client 2.20.4__py3-none-any.whl → 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prefect/__init__.py +74 -110
- prefect/_internal/compatibility/deprecated.py +6 -115
- prefect/_internal/compatibility/experimental.py +4 -79
- prefect/_internal/compatibility/migration.py +166 -0
- prefect/_internal/concurrency/__init__.py +2 -2
- prefect/_internal/concurrency/api.py +1 -35
- prefect/_internal/concurrency/calls.py +0 -6
- prefect/_internal/concurrency/cancellation.py +0 -3
- prefect/_internal/concurrency/event_loop.py +0 -20
- prefect/_internal/concurrency/inspection.py +3 -3
- prefect/_internal/concurrency/primitives.py +1 -0
- prefect/_internal/concurrency/services.py +23 -0
- prefect/_internal/concurrency/threads.py +35 -0
- prefect/_internal/concurrency/waiters.py +0 -28
- prefect/_internal/integrations.py +7 -0
- prefect/_internal/pydantic/__init__.py +0 -45
- prefect/_internal/pydantic/annotations/pendulum.py +2 -2
- prefect/_internal/pydantic/v1_schema.py +21 -22
- prefect/_internal/pydantic/v2_schema.py +0 -2
- prefect/_internal/pydantic/v2_validated_func.py +18 -23
- prefect/_internal/pytz.py +1 -1
- prefect/_internal/retries.py +61 -0
- prefect/_internal/schemas/bases.py +45 -177
- prefect/_internal/schemas/fields.py +1 -43
- prefect/_internal/schemas/validators.py +47 -233
- prefect/agent.py +3 -695
- prefect/artifacts.py +173 -14
- prefect/automations.py +39 -4
- prefect/blocks/abstract.py +1 -1
- prefect/blocks/core.py +405 -153
- prefect/blocks/fields.py +2 -57
- prefect/blocks/notifications.py +43 -28
- prefect/blocks/redis.py +168 -0
- prefect/blocks/system.py +67 -20
- prefect/blocks/webhook.py +2 -9
- prefect/cache_policies.py +239 -0
- prefect/client/__init__.py +4 -0
- prefect/client/base.py +33 -27
- prefect/client/cloud.py +65 -20
- prefect/client/collections.py +1 -1
- prefect/client/orchestration.py +650 -442
- prefect/client/schemas/actions.py +115 -100
- prefect/client/schemas/filters.py +46 -52
- prefect/client/schemas/objects.py +228 -178
- prefect/client/schemas/responses.py +18 -36
- prefect/client/schemas/schedules.py +55 -36
- prefect/client/schemas/sorting.py +2 -0
- prefect/client/subscriptions.py +8 -7
- prefect/client/types/flexible_schedule_list.py +11 -0
- prefect/client/utilities.py +9 -6
- prefect/concurrency/asyncio.py +60 -11
- prefect/concurrency/context.py +24 -0
- prefect/concurrency/events.py +2 -2
- prefect/concurrency/services.py +46 -16
- prefect/concurrency/sync.py +51 -7
- prefect/concurrency/v1/asyncio.py +143 -0
- prefect/concurrency/v1/context.py +27 -0
- prefect/concurrency/v1/events.py +61 -0
- prefect/concurrency/v1/services.py +116 -0
- prefect/concurrency/v1/sync.py +92 -0
- prefect/context.py +246 -149
- prefect/deployments/__init__.py +33 -18
- prefect/deployments/base.py +10 -15
- prefect/deployments/deployments.py +2 -1048
- prefect/deployments/flow_runs.py +178 -0
- prefect/deployments/runner.py +72 -173
- prefect/deployments/schedules.py +31 -25
- prefect/deployments/steps/__init__.py +0 -1
- prefect/deployments/steps/core.py +7 -0
- prefect/deployments/steps/pull.py +15 -21
- prefect/deployments/steps/utility.py +2 -1
- prefect/docker/__init__.py +20 -0
- prefect/docker/docker_image.py +82 -0
- prefect/engine.py +15 -2475
- prefect/events/actions.py +17 -23
- prefect/events/cli/automations.py +20 -7
- prefect/events/clients.py +142 -80
- prefect/events/filters.py +14 -18
- prefect/events/related.py +74 -75
- prefect/events/schemas/__init__.py +0 -5
- prefect/events/schemas/automations.py +55 -46
- prefect/events/schemas/deployment_triggers.py +7 -197
- prefect/events/schemas/events.py +46 -65
- prefect/events/schemas/labelling.py +10 -14
- prefect/events/utilities.py +4 -5
- prefect/events/worker.py +23 -8
- prefect/exceptions.py +15 -0
- prefect/filesystems.py +30 -529
- prefect/flow_engine.py +827 -0
- prefect/flow_runs.py +379 -7
- prefect/flows.py +470 -360
- prefect/futures.py +382 -331
- prefect/infrastructure/__init__.py +5 -26
- prefect/infrastructure/base.py +3 -320
- prefect/infrastructure/provisioners/__init__.py +5 -3
- prefect/infrastructure/provisioners/cloud_run.py +13 -8
- prefect/infrastructure/provisioners/container_instance.py +14 -9
- prefect/infrastructure/provisioners/ecs.py +10 -8
- prefect/infrastructure/provisioners/modal.py +8 -5
- prefect/input/__init__.py +4 -0
- prefect/input/actions.py +2 -4
- prefect/input/run_input.py +9 -9
- prefect/logging/formatters.py +2 -4
- prefect/logging/handlers.py +9 -14
- prefect/logging/loggers.py +5 -5
- prefect/main.py +72 -0
- prefect/plugins.py +2 -64
- prefect/profiles.toml +16 -2
- prefect/records/__init__.py +1 -0
- prefect/records/base.py +223 -0
- prefect/records/filesystem.py +207 -0
- prefect/records/memory.py +178 -0
- prefect/records/result_store.py +64 -0
- prefect/results.py +577 -504
- prefect/runner/runner.py +117 -47
- prefect/runner/server.py +32 -34
- prefect/runner/storage.py +3 -12
- prefect/runner/submit.py +2 -10
- prefect/runner/utils.py +2 -2
- prefect/runtime/__init__.py +1 -0
- prefect/runtime/deployment.py +1 -0
- prefect/runtime/flow_run.py +40 -5
- prefect/runtime/task_run.py +1 -0
- prefect/serializers.py +28 -39
- prefect/server/api/collections_data/views/aggregate-worker-metadata.json +5 -14
- prefect/settings.py +209 -332
- prefect/states.py +160 -63
- prefect/task_engine.py +1478 -57
- prefect/task_runners.py +383 -287
- prefect/task_runs.py +240 -0
- prefect/task_worker.py +463 -0
- prefect/tasks.py +684 -374
- prefect/transactions.py +410 -0
- prefect/types/__init__.py +72 -86
- prefect/types/entrypoint.py +13 -0
- prefect/utilities/annotations.py +4 -3
- prefect/utilities/asyncutils.py +227 -148
- prefect/utilities/callables.py +137 -45
- prefect/utilities/collections.py +134 -86
- prefect/utilities/dispatch.py +27 -14
- prefect/utilities/dockerutils.py +11 -4
- prefect/utilities/engine.py +186 -32
- prefect/utilities/filesystem.py +4 -5
- prefect/utilities/importtools.py +26 -27
- prefect/utilities/pydantic.py +128 -38
- prefect/utilities/schema_tools/hydration.py +18 -1
- prefect/utilities/schema_tools/validation.py +30 -0
- prefect/utilities/services.py +35 -9
- prefect/utilities/templating.py +12 -2
- prefect/utilities/timeout.py +20 -5
- prefect/utilities/urls.py +195 -0
- prefect/utilities/visualization.py +1 -0
- prefect/variables.py +78 -59
- prefect/workers/__init__.py +0 -1
- prefect/workers/base.py +237 -244
- prefect/workers/block.py +5 -226
- prefect/workers/cloud.py +6 -0
- prefect/workers/process.py +265 -12
- prefect/workers/server.py +29 -11
- {prefect_client-2.20.4.dist-info → prefect_client-3.0.0.dist-info}/METADATA +28 -24
- prefect_client-3.0.0.dist-info/RECORD +201 -0
- {prefect_client-2.20.4.dist-info → prefect_client-3.0.0.dist-info}/WHEEL +1 -1
- prefect/_internal/pydantic/_base_model.py +0 -51
- prefect/_internal/pydantic/_compat.py +0 -82
- prefect/_internal/pydantic/_flags.py +0 -20
- prefect/_internal/pydantic/_types.py +0 -8
- prefect/_internal/pydantic/utilities/config_dict.py +0 -72
- prefect/_internal/pydantic/utilities/field_validator.py +0 -150
- prefect/_internal/pydantic/utilities/model_construct.py +0 -56
- prefect/_internal/pydantic/utilities/model_copy.py +0 -55
- prefect/_internal/pydantic/utilities/model_dump.py +0 -136
- prefect/_internal/pydantic/utilities/model_dump_json.py +0 -112
- prefect/_internal/pydantic/utilities/model_fields.py +0 -50
- prefect/_internal/pydantic/utilities/model_fields_set.py +0 -29
- prefect/_internal/pydantic/utilities/model_json_schema.py +0 -82
- prefect/_internal/pydantic/utilities/model_rebuild.py +0 -80
- prefect/_internal/pydantic/utilities/model_validate.py +0 -75
- prefect/_internal/pydantic/utilities/model_validate_json.py +0 -68
- prefect/_internal/pydantic/utilities/model_validator.py +0 -87
- prefect/_internal/pydantic/utilities/type_adapter.py +0 -71
- prefect/_vendor/fastapi/__init__.py +0 -25
- prefect/_vendor/fastapi/applications.py +0 -946
- prefect/_vendor/fastapi/background.py +0 -3
- prefect/_vendor/fastapi/concurrency.py +0 -44
- prefect/_vendor/fastapi/datastructures.py +0 -58
- prefect/_vendor/fastapi/dependencies/__init__.py +0 -0
- prefect/_vendor/fastapi/dependencies/models.py +0 -64
- prefect/_vendor/fastapi/dependencies/utils.py +0 -877
- prefect/_vendor/fastapi/encoders.py +0 -177
- prefect/_vendor/fastapi/exception_handlers.py +0 -40
- prefect/_vendor/fastapi/exceptions.py +0 -46
- prefect/_vendor/fastapi/logger.py +0 -3
- prefect/_vendor/fastapi/middleware/__init__.py +0 -1
- prefect/_vendor/fastapi/middleware/asyncexitstack.py +0 -25
- prefect/_vendor/fastapi/middleware/cors.py +0 -3
- prefect/_vendor/fastapi/middleware/gzip.py +0 -3
- prefect/_vendor/fastapi/middleware/httpsredirect.py +0 -3
- prefect/_vendor/fastapi/middleware/trustedhost.py +0 -3
- prefect/_vendor/fastapi/middleware/wsgi.py +0 -3
- prefect/_vendor/fastapi/openapi/__init__.py +0 -0
- prefect/_vendor/fastapi/openapi/constants.py +0 -2
- prefect/_vendor/fastapi/openapi/docs.py +0 -203
- prefect/_vendor/fastapi/openapi/models.py +0 -480
- prefect/_vendor/fastapi/openapi/utils.py +0 -485
- prefect/_vendor/fastapi/param_functions.py +0 -340
- prefect/_vendor/fastapi/params.py +0 -453
- prefect/_vendor/fastapi/py.typed +0 -0
- prefect/_vendor/fastapi/requests.py +0 -4
- prefect/_vendor/fastapi/responses.py +0 -40
- prefect/_vendor/fastapi/routing.py +0 -1331
- prefect/_vendor/fastapi/security/__init__.py +0 -15
- prefect/_vendor/fastapi/security/api_key.py +0 -98
- prefect/_vendor/fastapi/security/base.py +0 -6
- prefect/_vendor/fastapi/security/http.py +0 -172
- prefect/_vendor/fastapi/security/oauth2.py +0 -227
- prefect/_vendor/fastapi/security/open_id_connect_url.py +0 -34
- prefect/_vendor/fastapi/security/utils.py +0 -10
- prefect/_vendor/fastapi/staticfiles.py +0 -1
- prefect/_vendor/fastapi/templating.py +0 -3
- prefect/_vendor/fastapi/testclient.py +0 -1
- prefect/_vendor/fastapi/types.py +0 -3
- prefect/_vendor/fastapi/utils.py +0 -235
- prefect/_vendor/fastapi/websockets.py +0 -7
- prefect/_vendor/starlette/__init__.py +0 -1
- prefect/_vendor/starlette/_compat.py +0 -28
- prefect/_vendor/starlette/_exception_handler.py +0 -80
- prefect/_vendor/starlette/_utils.py +0 -88
- prefect/_vendor/starlette/applications.py +0 -261
- prefect/_vendor/starlette/authentication.py +0 -159
- prefect/_vendor/starlette/background.py +0 -43
- prefect/_vendor/starlette/concurrency.py +0 -59
- prefect/_vendor/starlette/config.py +0 -151
- prefect/_vendor/starlette/convertors.py +0 -87
- prefect/_vendor/starlette/datastructures.py +0 -707
- prefect/_vendor/starlette/endpoints.py +0 -130
- prefect/_vendor/starlette/exceptions.py +0 -60
- prefect/_vendor/starlette/formparsers.py +0 -276
- prefect/_vendor/starlette/middleware/__init__.py +0 -17
- prefect/_vendor/starlette/middleware/authentication.py +0 -52
- prefect/_vendor/starlette/middleware/base.py +0 -220
- prefect/_vendor/starlette/middleware/cors.py +0 -176
- prefect/_vendor/starlette/middleware/errors.py +0 -265
- prefect/_vendor/starlette/middleware/exceptions.py +0 -74
- prefect/_vendor/starlette/middleware/gzip.py +0 -113
- prefect/_vendor/starlette/middleware/httpsredirect.py +0 -19
- prefect/_vendor/starlette/middleware/sessions.py +0 -82
- prefect/_vendor/starlette/middleware/trustedhost.py +0 -64
- prefect/_vendor/starlette/middleware/wsgi.py +0 -147
- prefect/_vendor/starlette/py.typed +0 -0
- prefect/_vendor/starlette/requests.py +0 -328
- prefect/_vendor/starlette/responses.py +0 -347
- prefect/_vendor/starlette/routing.py +0 -933
- prefect/_vendor/starlette/schemas.py +0 -154
- prefect/_vendor/starlette/staticfiles.py +0 -248
- prefect/_vendor/starlette/status.py +0 -199
- prefect/_vendor/starlette/templating.py +0 -231
- prefect/_vendor/starlette/testclient.py +0 -804
- prefect/_vendor/starlette/types.py +0 -30
- prefect/_vendor/starlette/websockets.py +0 -193
- prefect/blocks/kubernetes.py +0 -119
- prefect/deprecated/__init__.py +0 -0
- prefect/deprecated/data_documents.py +0 -350
- prefect/deprecated/packaging/__init__.py +0 -12
- prefect/deprecated/packaging/base.py +0 -96
- prefect/deprecated/packaging/docker.py +0 -146
- prefect/deprecated/packaging/file.py +0 -92
- prefect/deprecated/packaging/orion.py +0 -80
- prefect/deprecated/packaging/serializers.py +0 -171
- prefect/events/instrument.py +0 -135
- prefect/infrastructure/container.py +0 -824
- prefect/infrastructure/kubernetes.py +0 -920
- prefect/infrastructure/process.py +0 -289
- prefect/manifests.py +0 -20
- prefect/new_flow_engine.py +0 -449
- prefect/new_task_engine.py +0 -423
- prefect/pydantic/__init__.py +0 -76
- prefect/pydantic/main.py +0 -39
- prefect/software/__init__.py +0 -2
- prefect/software/base.py +0 -50
- prefect/software/conda.py +0 -199
- prefect/software/pip.py +0 -122
- prefect/software/python.py +0 -52
- prefect/task_server.py +0 -322
- prefect_client-2.20.4.dist-info/RECORD +0 -294
- /prefect/{_internal/pydantic/utilities → client/types}/__init__.py +0 -0
- /prefect/{_vendor → concurrency/v1}/__init__.py +0 -0
- {prefect_client-2.20.4.dist-info → prefect_client-3.0.0.dist-info}/LICENSE +0 -0
- {prefect_client-2.20.4.dist-info → prefect_client-3.0.0.dist-info}/top_level.txt +0 -0
@@ -1,933 +0,0 @@
|
|
1
|
-
import contextlib
|
2
|
-
import functools
|
3
|
-
import inspect
|
4
|
-
import re
|
5
|
-
import traceback
|
6
|
-
import types
|
7
|
-
import typing
|
8
|
-
import warnings
|
9
|
-
from contextlib import asynccontextmanager
|
10
|
-
from enum import Enum
|
11
|
-
|
12
|
-
from prefect._vendor.starlette._exception_handler import wrap_app_handling_exceptions
|
13
|
-
from prefect._vendor.starlette._utils import is_async_callable
|
14
|
-
from prefect._vendor.starlette.concurrency import run_in_threadpool
|
15
|
-
from prefect._vendor.starlette.convertors import CONVERTOR_TYPES, Convertor
|
16
|
-
from prefect._vendor.starlette.datastructures import URL, Headers, URLPath
|
17
|
-
from prefect._vendor.starlette.exceptions import HTTPException
|
18
|
-
from prefect._vendor.starlette.middleware import Middleware
|
19
|
-
from prefect._vendor.starlette.requests import Request
|
20
|
-
from prefect._vendor.starlette.responses import (
|
21
|
-
PlainTextResponse,
|
22
|
-
RedirectResponse,
|
23
|
-
Response,
|
24
|
-
)
|
25
|
-
from prefect._vendor.starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
|
26
|
-
from prefect._vendor.starlette.websockets import WebSocket, WebSocketClose
|
27
|
-
|
28
|
-
|
29
|
-
class NoMatchFound(Exception):
|
30
|
-
"""
|
31
|
-
Raised by `.url_for(name, **path_params)` and `.url_path_for(name, **path_params)`
|
32
|
-
if no matching route exists.
|
33
|
-
"""
|
34
|
-
|
35
|
-
def __init__(self, name: str, path_params: typing.Dict[str, typing.Any]) -> None:
|
36
|
-
params = ", ".join(list(path_params.keys()))
|
37
|
-
super().__init__(f'No route exists for name "{name}" and params "{params}".')
|
38
|
-
|
39
|
-
|
40
|
-
class Match(Enum):
|
41
|
-
NONE = 0
|
42
|
-
PARTIAL = 1
|
43
|
-
FULL = 2
|
44
|
-
|
45
|
-
|
46
|
-
def iscoroutinefunction_or_partial(obj: typing.Any) -> bool: # pragma: no cover
|
47
|
-
"""
|
48
|
-
Correctly determines if an object is a coroutine function,
|
49
|
-
including those wrapped in functools.partial objects.
|
50
|
-
"""
|
51
|
-
warnings.warn(
|
52
|
-
"iscoroutinefunction_or_partial is deprecated, "
|
53
|
-
"and will be removed in a future release.",
|
54
|
-
DeprecationWarning,
|
55
|
-
)
|
56
|
-
while isinstance(obj, functools.partial):
|
57
|
-
obj = obj.func
|
58
|
-
return inspect.iscoroutinefunction(obj)
|
59
|
-
|
60
|
-
|
61
|
-
def request_response(
|
62
|
-
func: typing.Callable[
|
63
|
-
[Request], typing.Union[typing.Awaitable[Response], Response]
|
64
|
-
],
|
65
|
-
) -> ASGIApp:
|
66
|
-
"""
|
67
|
-
Takes a function or coroutine `func(request) -> response`,
|
68
|
-
and returns an ASGI application.
|
69
|
-
"""
|
70
|
-
|
71
|
-
async def app(scope: Scope, receive: Receive, send: Send) -> None:
|
72
|
-
request = Request(scope, receive, send)
|
73
|
-
|
74
|
-
async def app(scope: Scope, receive: Receive, send: Send) -> None:
|
75
|
-
if is_async_callable(func):
|
76
|
-
response = await func(request)
|
77
|
-
else:
|
78
|
-
response = await run_in_threadpool(func, request)
|
79
|
-
await response(scope, receive, send)
|
80
|
-
|
81
|
-
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
|
82
|
-
|
83
|
-
return app
|
84
|
-
|
85
|
-
|
86
|
-
def websocket_session(
|
87
|
-
func: typing.Callable[[WebSocket], typing.Awaitable[None]],
|
88
|
-
) -> ASGIApp:
|
89
|
-
"""
|
90
|
-
Takes a coroutine `func(session)`, and returns an ASGI application.
|
91
|
-
"""
|
92
|
-
# assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
|
93
|
-
|
94
|
-
async def app(scope: Scope, receive: Receive, send: Send) -> None:
|
95
|
-
session = WebSocket(scope, receive=receive, send=send)
|
96
|
-
|
97
|
-
async def app(scope: Scope, receive: Receive, send: Send) -> None:
|
98
|
-
await func(session)
|
99
|
-
|
100
|
-
await wrap_app_handling_exceptions(app, session)(scope, receive, send)
|
101
|
-
|
102
|
-
return app
|
103
|
-
|
104
|
-
|
105
|
-
def get_name(endpoint: typing.Callable[..., typing.Any]) -> str:
|
106
|
-
if inspect.isroutine(endpoint) or inspect.isclass(endpoint):
|
107
|
-
return endpoint.__name__
|
108
|
-
return endpoint.__class__.__name__
|
109
|
-
|
110
|
-
|
111
|
-
def replace_params(
|
112
|
-
path: str,
|
113
|
-
param_convertors: typing.Dict[str, Convertor[typing.Any]],
|
114
|
-
path_params: typing.Dict[str, str],
|
115
|
-
) -> typing.Tuple[str, typing.Dict[str, str]]:
|
116
|
-
for key, value in list(path_params.items()):
|
117
|
-
if "{" + key + "}" in path:
|
118
|
-
convertor = param_convertors[key]
|
119
|
-
value = convertor.to_string(value)
|
120
|
-
path = path.replace("{" + key + "}", value)
|
121
|
-
path_params.pop(key)
|
122
|
-
return path, path_params
|
123
|
-
|
124
|
-
|
125
|
-
# Match parameters in URL paths, eg. '{param}', and '{param:int}'
|
126
|
-
PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}")
|
127
|
-
|
128
|
-
|
129
|
-
def compile_path(
|
130
|
-
path: str,
|
131
|
-
) -> typing.Tuple[typing.Pattern[str], str, typing.Dict[str, Convertor[typing.Any]]]:
|
132
|
-
"""
|
133
|
-
Given a path string, like: "/{username:str}",
|
134
|
-
or a host string, like: "{subdomain}.mydomain.org", return a three-tuple
|
135
|
-
of (regex, format, {param_name:convertor}).
|
136
|
-
|
137
|
-
regex: "/(?P<username>[^/]+)"
|
138
|
-
format: "/{username}"
|
139
|
-
convertors: {"username": StringConvertor()}
|
140
|
-
"""
|
141
|
-
is_host = not path.startswith("/")
|
142
|
-
|
143
|
-
path_regex = "^"
|
144
|
-
path_format = ""
|
145
|
-
duplicated_params = set()
|
146
|
-
|
147
|
-
idx = 0
|
148
|
-
param_convertors = {}
|
149
|
-
for match in PARAM_REGEX.finditer(path):
|
150
|
-
param_name, convertor_type = match.groups("str")
|
151
|
-
convertor_type = convertor_type.lstrip(":")
|
152
|
-
assert (
|
153
|
-
convertor_type in CONVERTOR_TYPES
|
154
|
-
), f"Unknown path convertor '{convertor_type}'"
|
155
|
-
convertor = CONVERTOR_TYPES[convertor_type]
|
156
|
-
|
157
|
-
path_regex += re.escape(path[idx : match.start()])
|
158
|
-
path_regex += f"(?P<{param_name}>{convertor.regex})"
|
159
|
-
|
160
|
-
path_format += path[idx : match.start()]
|
161
|
-
path_format += "{%s}" % param_name
|
162
|
-
|
163
|
-
if param_name in param_convertors:
|
164
|
-
duplicated_params.add(param_name)
|
165
|
-
|
166
|
-
param_convertors[param_name] = convertor
|
167
|
-
|
168
|
-
idx = match.end()
|
169
|
-
|
170
|
-
if duplicated_params:
|
171
|
-
names = ", ".join(sorted(duplicated_params))
|
172
|
-
ending = "s" if len(duplicated_params) > 1 else ""
|
173
|
-
raise ValueError(f"Duplicated param name{ending} {names} at path {path}")
|
174
|
-
|
175
|
-
if is_host:
|
176
|
-
# Align with `Host.matches()` behavior, which ignores port.
|
177
|
-
hostname = path[idx:].split(":")[0]
|
178
|
-
path_regex += re.escape(hostname) + "$"
|
179
|
-
else:
|
180
|
-
path_regex += re.escape(path[idx:]) + "$"
|
181
|
-
|
182
|
-
path_format += path[idx:]
|
183
|
-
|
184
|
-
return re.compile(path_regex), path_format, param_convertors
|
185
|
-
|
186
|
-
|
187
|
-
class BaseRoute:
|
188
|
-
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
|
189
|
-
raise NotImplementedError() # pragma: no cover
|
190
|
-
|
191
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
192
|
-
raise NotImplementedError() # pragma: no cover
|
193
|
-
|
194
|
-
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
195
|
-
raise NotImplementedError() # pragma: no cover
|
196
|
-
|
197
|
-
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
198
|
-
"""
|
199
|
-
A route may be used in isolation as a stand-alone ASGI app.
|
200
|
-
This is a somewhat contrived case, as they'll almost always be used
|
201
|
-
within a Router, but could be useful for some tooling and minimal apps.
|
202
|
-
"""
|
203
|
-
match, child_scope = self.matches(scope)
|
204
|
-
if match == Match.NONE:
|
205
|
-
if scope["type"] == "http":
|
206
|
-
response = PlainTextResponse("Not Found", status_code=404)
|
207
|
-
await response(scope, receive, send)
|
208
|
-
elif scope["type"] == "websocket":
|
209
|
-
websocket_close = WebSocketClose()
|
210
|
-
await websocket_close(scope, receive, send)
|
211
|
-
return
|
212
|
-
|
213
|
-
scope.update(child_scope)
|
214
|
-
await self.handle(scope, receive, send)
|
215
|
-
|
216
|
-
|
217
|
-
class Route(BaseRoute):
|
218
|
-
def __init__(
|
219
|
-
self,
|
220
|
-
path: str,
|
221
|
-
endpoint: typing.Callable[..., typing.Any],
|
222
|
-
*,
|
223
|
-
methods: typing.Optional[typing.List[str]] = None,
|
224
|
-
name: typing.Optional[str] = None,
|
225
|
-
include_in_schema: bool = True,
|
226
|
-
middleware: typing.Optional[typing.Sequence[Middleware]] = None,
|
227
|
-
) -> None:
|
228
|
-
assert path.startswith("/"), "Routed paths must start with '/'"
|
229
|
-
self.path = path
|
230
|
-
self.endpoint = endpoint
|
231
|
-
self.name = get_name(endpoint) if name is None else name
|
232
|
-
self.include_in_schema = include_in_schema
|
233
|
-
|
234
|
-
endpoint_handler = endpoint
|
235
|
-
while isinstance(endpoint_handler, functools.partial):
|
236
|
-
endpoint_handler = endpoint_handler.func
|
237
|
-
if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
|
238
|
-
# Endpoint is function or method. Treat it as `func(request) -> response`.
|
239
|
-
self.app = request_response(endpoint)
|
240
|
-
if methods is None:
|
241
|
-
methods = ["GET"]
|
242
|
-
else:
|
243
|
-
# Endpoint is a class. Treat it as ASGI.
|
244
|
-
self.app = endpoint
|
245
|
-
|
246
|
-
if middleware is not None:
|
247
|
-
for cls, options in reversed(middleware):
|
248
|
-
self.app = cls(app=self.app, **options)
|
249
|
-
|
250
|
-
if methods is None:
|
251
|
-
self.methods = None
|
252
|
-
else:
|
253
|
-
self.methods = {method.upper() for method in methods}
|
254
|
-
if "GET" in self.methods:
|
255
|
-
self.methods.add("HEAD")
|
256
|
-
|
257
|
-
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
|
258
|
-
|
259
|
-
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
|
260
|
-
path_params: "typing.Dict[str, typing.Any]"
|
261
|
-
if scope["type"] == "http":
|
262
|
-
root_path = scope.get("route_root_path", scope.get("root_path", ""))
|
263
|
-
path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"]))
|
264
|
-
match = self.path_regex.match(path)
|
265
|
-
if match:
|
266
|
-
matched_params = match.groupdict()
|
267
|
-
for key, value in matched_params.items():
|
268
|
-
matched_params[key] = self.param_convertors[key].convert(value)
|
269
|
-
path_params = dict(scope.get("path_params", {}))
|
270
|
-
path_params.update(matched_params)
|
271
|
-
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
|
272
|
-
if self.methods and scope["method"] not in self.methods:
|
273
|
-
return Match.PARTIAL, child_scope
|
274
|
-
else:
|
275
|
-
return Match.FULL, child_scope
|
276
|
-
return Match.NONE, {}
|
277
|
-
|
278
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
279
|
-
seen_params = set(path_params.keys())
|
280
|
-
expected_params = set(self.param_convertors.keys())
|
281
|
-
|
282
|
-
if name != self.name or seen_params != expected_params:
|
283
|
-
raise NoMatchFound(name, path_params)
|
284
|
-
|
285
|
-
path, remaining_params = replace_params(
|
286
|
-
self.path_format, self.param_convertors, path_params
|
287
|
-
)
|
288
|
-
assert not remaining_params
|
289
|
-
return URLPath(path=path, protocol="http")
|
290
|
-
|
291
|
-
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
292
|
-
if self.methods and scope["method"] not in self.methods:
|
293
|
-
headers = {"Allow": ", ".join(self.methods)}
|
294
|
-
if "app" in scope:
|
295
|
-
raise HTTPException(status_code=405, headers=headers)
|
296
|
-
else:
|
297
|
-
response = PlainTextResponse(
|
298
|
-
"Method Not Allowed", status_code=405, headers=headers
|
299
|
-
)
|
300
|
-
await response(scope, receive, send)
|
301
|
-
else:
|
302
|
-
await self.app(scope, receive, send)
|
303
|
-
|
304
|
-
def __eq__(self, other: typing.Any) -> bool:
|
305
|
-
return (
|
306
|
-
isinstance(other, Route)
|
307
|
-
and self.path == other.path
|
308
|
-
and self.endpoint == other.endpoint
|
309
|
-
and self.methods == other.methods
|
310
|
-
)
|
311
|
-
|
312
|
-
def __repr__(self) -> str:
|
313
|
-
class_name = self.__class__.__name__
|
314
|
-
methods = sorted(self.methods or [])
|
315
|
-
path, name = self.path, self.name
|
316
|
-
return f"{class_name}(path={path!r}, name={name!r}, methods={methods!r})"
|
317
|
-
|
318
|
-
|
319
|
-
class WebSocketRoute(BaseRoute):
|
320
|
-
def __init__(
|
321
|
-
self,
|
322
|
-
path: str,
|
323
|
-
endpoint: typing.Callable[..., typing.Any],
|
324
|
-
*,
|
325
|
-
name: typing.Optional[str] = None,
|
326
|
-
middleware: typing.Optional[typing.Sequence[Middleware]] = None,
|
327
|
-
) -> None:
|
328
|
-
assert path.startswith("/"), "Routed paths must start with '/'"
|
329
|
-
self.path = path
|
330
|
-
self.endpoint = endpoint
|
331
|
-
self.name = get_name(endpoint) if name is None else name
|
332
|
-
|
333
|
-
endpoint_handler = endpoint
|
334
|
-
while isinstance(endpoint_handler, functools.partial):
|
335
|
-
endpoint_handler = endpoint_handler.func
|
336
|
-
if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
|
337
|
-
# Endpoint is function or method. Treat it as `func(websocket)`.
|
338
|
-
self.app = websocket_session(endpoint)
|
339
|
-
else:
|
340
|
-
# Endpoint is a class. Treat it as ASGI.
|
341
|
-
self.app = endpoint
|
342
|
-
|
343
|
-
if middleware is not None:
|
344
|
-
for cls, options in reversed(middleware):
|
345
|
-
self.app = cls(app=self.app, **options)
|
346
|
-
|
347
|
-
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
|
348
|
-
|
349
|
-
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
|
350
|
-
path_params: "typing.Dict[str, typing.Any]"
|
351
|
-
if scope["type"] == "websocket":
|
352
|
-
root_path = scope.get("route_root_path", scope.get("root_path", ""))
|
353
|
-
path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"]))
|
354
|
-
match = self.path_regex.match(path)
|
355
|
-
if match:
|
356
|
-
matched_params = match.groupdict()
|
357
|
-
for key, value in matched_params.items():
|
358
|
-
matched_params[key] = self.param_convertors[key].convert(value)
|
359
|
-
path_params = dict(scope.get("path_params", {}))
|
360
|
-
path_params.update(matched_params)
|
361
|
-
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
|
362
|
-
return Match.FULL, child_scope
|
363
|
-
return Match.NONE, {}
|
364
|
-
|
365
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
366
|
-
seen_params = set(path_params.keys())
|
367
|
-
expected_params = set(self.param_convertors.keys())
|
368
|
-
|
369
|
-
if name != self.name or seen_params != expected_params:
|
370
|
-
raise NoMatchFound(name, path_params)
|
371
|
-
|
372
|
-
path, remaining_params = replace_params(
|
373
|
-
self.path_format, self.param_convertors, path_params
|
374
|
-
)
|
375
|
-
assert not remaining_params
|
376
|
-
return URLPath(path=path, protocol="websocket")
|
377
|
-
|
378
|
-
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
379
|
-
await self.app(scope, receive, send)
|
380
|
-
|
381
|
-
def __eq__(self, other: typing.Any) -> bool:
|
382
|
-
return (
|
383
|
-
isinstance(other, WebSocketRoute)
|
384
|
-
and self.path == other.path
|
385
|
-
and self.endpoint == other.endpoint
|
386
|
-
)
|
387
|
-
|
388
|
-
def __repr__(self) -> str:
|
389
|
-
return f"{self.__class__.__name__}(path={self.path!r}, name={self.name!r})"
|
390
|
-
|
391
|
-
|
392
|
-
class Mount(BaseRoute):
|
393
|
-
def __init__(
|
394
|
-
self,
|
395
|
-
path: str,
|
396
|
-
app: typing.Optional[ASGIApp] = None,
|
397
|
-
routes: typing.Optional[typing.Sequence[BaseRoute]] = None,
|
398
|
-
name: typing.Optional[str] = None,
|
399
|
-
*,
|
400
|
-
middleware: typing.Optional[typing.Sequence[Middleware]] = None,
|
401
|
-
) -> None:
|
402
|
-
assert path == "" or path.startswith("/"), "Routed paths must start with '/'"
|
403
|
-
assert (
|
404
|
-
app is not None or routes is not None
|
405
|
-
), "Either 'app=...', or 'routes=' must be specified"
|
406
|
-
self.path = path.rstrip("/")
|
407
|
-
if app is not None:
|
408
|
-
self._base_app: ASGIApp = app
|
409
|
-
else:
|
410
|
-
self._base_app = Router(routes=routes)
|
411
|
-
self.app = self._base_app
|
412
|
-
if middleware is not None:
|
413
|
-
for cls, options in reversed(middleware):
|
414
|
-
self.app = cls(app=self.app, **options)
|
415
|
-
self.name = name
|
416
|
-
self.path_regex, self.path_format, self.param_convertors = compile_path(
|
417
|
-
self.path + "/{path:path}"
|
418
|
-
)
|
419
|
-
|
420
|
-
@property
|
421
|
-
def routes(self) -> typing.List[BaseRoute]:
|
422
|
-
return getattr(self._base_app, "routes", [])
|
423
|
-
|
424
|
-
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
|
425
|
-
path_params: "typing.Dict[str, typing.Any]"
|
426
|
-
if scope["type"] in ("http", "websocket"):
|
427
|
-
path = scope["path"]
|
428
|
-
root_path = scope.get("route_root_path", scope.get("root_path", ""))
|
429
|
-
route_path = scope.get("route_path", re.sub(r"^" + root_path, "", path))
|
430
|
-
match = self.path_regex.match(route_path)
|
431
|
-
if match:
|
432
|
-
matched_params = match.groupdict()
|
433
|
-
for key, value in matched_params.items():
|
434
|
-
matched_params[key] = self.param_convertors[key].convert(value)
|
435
|
-
remaining_path = "/" + matched_params.pop("path")
|
436
|
-
matched_path = route_path[: -len(remaining_path)]
|
437
|
-
path_params = dict(scope.get("path_params", {}))
|
438
|
-
path_params.update(matched_params)
|
439
|
-
root_path = scope.get("root_path", "")
|
440
|
-
child_scope = {
|
441
|
-
"path_params": path_params,
|
442
|
-
"route_root_path": root_path + matched_path,
|
443
|
-
"route_path": remaining_path,
|
444
|
-
"endpoint": self.app,
|
445
|
-
}
|
446
|
-
return Match.FULL, child_scope
|
447
|
-
return Match.NONE, {}
|
448
|
-
|
449
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
450
|
-
if self.name is not None and name == self.name and "path" in path_params:
|
451
|
-
# 'name' matches "<mount_name>".
|
452
|
-
path_params["path"] = path_params["path"].lstrip("/")
|
453
|
-
path, remaining_params = replace_params(
|
454
|
-
self.path_format, self.param_convertors, path_params
|
455
|
-
)
|
456
|
-
if not remaining_params:
|
457
|
-
return URLPath(path=path)
|
458
|
-
elif self.name is None or name.startswith(self.name + ":"):
|
459
|
-
if self.name is None:
|
460
|
-
# No mount name.
|
461
|
-
remaining_name = name
|
462
|
-
else:
|
463
|
-
# 'name' matches "<mount_name>:<child_name>".
|
464
|
-
remaining_name = name[len(self.name) + 1 :]
|
465
|
-
path_kwarg = path_params.get("path")
|
466
|
-
path_params["path"] = ""
|
467
|
-
path_prefix, remaining_params = replace_params(
|
468
|
-
self.path_format, self.param_convertors, path_params
|
469
|
-
)
|
470
|
-
if path_kwarg is not None:
|
471
|
-
remaining_params["path"] = path_kwarg
|
472
|
-
for route in self.routes or []:
|
473
|
-
try:
|
474
|
-
url = route.url_path_for(remaining_name, **remaining_params)
|
475
|
-
return URLPath(
|
476
|
-
path=path_prefix.rstrip("/") + str(url), protocol=url.protocol
|
477
|
-
)
|
478
|
-
except NoMatchFound:
|
479
|
-
pass
|
480
|
-
raise NoMatchFound(name, path_params)
|
481
|
-
|
482
|
-
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
483
|
-
await self.app(scope, receive, send)
|
484
|
-
|
485
|
-
def __eq__(self, other: typing.Any) -> bool:
|
486
|
-
return (
|
487
|
-
isinstance(other, Mount)
|
488
|
-
and self.path == other.path
|
489
|
-
and self.app == other.app
|
490
|
-
)
|
491
|
-
|
492
|
-
def __repr__(self) -> str:
|
493
|
-
class_name = self.__class__.__name__
|
494
|
-
name = self.name or ""
|
495
|
-
return f"{class_name}(path={self.path!r}, name={name!r}, app={self.app!r})"
|
496
|
-
|
497
|
-
|
498
|
-
class Host(BaseRoute):
|
499
|
-
def __init__(
|
500
|
-
self, host: str, app: ASGIApp, name: typing.Optional[str] = None
|
501
|
-
) -> None:
|
502
|
-
assert not host.startswith("/"), "Host must not start with '/'"
|
503
|
-
self.host = host
|
504
|
-
self.app = app
|
505
|
-
self.name = name
|
506
|
-
self.host_regex, self.host_format, self.param_convertors = compile_path(host)
|
507
|
-
|
508
|
-
@property
|
509
|
-
def routes(self) -> typing.List[BaseRoute]:
|
510
|
-
return getattr(self.app, "routes", [])
|
511
|
-
|
512
|
-
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
|
513
|
-
if scope["type"] in ("http", "websocket"):
|
514
|
-
headers = Headers(scope=scope)
|
515
|
-
host = headers.get("host", "").split(":")[0]
|
516
|
-
match = self.host_regex.match(host)
|
517
|
-
if match:
|
518
|
-
matched_params = match.groupdict()
|
519
|
-
for key, value in matched_params.items():
|
520
|
-
matched_params[key] = self.param_convertors[key].convert(value)
|
521
|
-
path_params = dict(scope.get("path_params", {}))
|
522
|
-
path_params.update(matched_params)
|
523
|
-
child_scope = {"path_params": path_params, "endpoint": self.app}
|
524
|
-
return Match.FULL, child_scope
|
525
|
-
return Match.NONE, {}
|
526
|
-
|
527
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
528
|
-
if self.name is not None and name == self.name and "path" in path_params:
|
529
|
-
# 'name' matches "<mount_name>".
|
530
|
-
path = path_params.pop("path")
|
531
|
-
host, remaining_params = replace_params(
|
532
|
-
self.host_format, self.param_convertors, path_params
|
533
|
-
)
|
534
|
-
if not remaining_params:
|
535
|
-
return URLPath(path=path, host=host)
|
536
|
-
elif self.name is None or name.startswith(self.name + ":"):
|
537
|
-
if self.name is None:
|
538
|
-
# No mount name.
|
539
|
-
remaining_name = name
|
540
|
-
else:
|
541
|
-
# 'name' matches "<mount_name>:<child_name>".
|
542
|
-
remaining_name = name[len(self.name) + 1 :]
|
543
|
-
host, remaining_params = replace_params(
|
544
|
-
self.host_format, self.param_convertors, path_params
|
545
|
-
)
|
546
|
-
for route in self.routes or []:
|
547
|
-
try:
|
548
|
-
url = route.url_path_for(remaining_name, **remaining_params)
|
549
|
-
return URLPath(path=str(url), protocol=url.protocol, host=host)
|
550
|
-
except NoMatchFound:
|
551
|
-
pass
|
552
|
-
raise NoMatchFound(name, path_params)
|
553
|
-
|
554
|
-
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
|
555
|
-
await self.app(scope, receive, send)
|
556
|
-
|
557
|
-
def __eq__(self, other: typing.Any) -> bool:
|
558
|
-
return (
|
559
|
-
isinstance(other, Host)
|
560
|
-
and self.host == other.host
|
561
|
-
and self.app == other.app
|
562
|
-
)
|
563
|
-
|
564
|
-
def __repr__(self) -> str:
|
565
|
-
class_name = self.__class__.__name__
|
566
|
-
name = self.name or ""
|
567
|
-
return f"{class_name}(host={self.host!r}, name={name!r}, app={self.app!r})"
|
568
|
-
|
569
|
-
|
570
|
-
_T = typing.TypeVar("_T")
|
571
|
-
|
572
|
-
|
573
|
-
class _AsyncLiftContextManager(typing.AsyncContextManager[_T]):
|
574
|
-
def __init__(self, cm: typing.ContextManager[_T]):
|
575
|
-
self._cm = cm
|
576
|
-
|
577
|
-
async def __aenter__(self) -> _T:
|
578
|
-
return self._cm.__enter__()
|
579
|
-
|
580
|
-
async def __aexit__(
|
581
|
-
self,
|
582
|
-
exc_type: typing.Optional[typing.Type[BaseException]],
|
583
|
-
exc_value: typing.Optional[BaseException],
|
584
|
-
traceback: typing.Optional[types.TracebackType],
|
585
|
-
) -> typing.Optional[bool]:
|
586
|
-
return self._cm.__exit__(exc_type, exc_value, traceback)
|
587
|
-
|
588
|
-
|
589
|
-
def _wrap_gen_lifespan_context(
|
590
|
-
lifespan_context: typing.Callable[
|
591
|
-
[typing.Any], typing.Generator[typing.Any, typing.Any, typing.Any]
|
592
|
-
],
|
593
|
-
) -> typing.Callable[[typing.Any], typing.AsyncContextManager[typing.Any]]:
|
594
|
-
cmgr = contextlib.contextmanager(lifespan_context)
|
595
|
-
|
596
|
-
@functools.wraps(cmgr)
|
597
|
-
def wrapper(app: typing.Any) -> _AsyncLiftContextManager[typing.Any]:
|
598
|
-
return _AsyncLiftContextManager(cmgr(app))
|
599
|
-
|
600
|
-
return wrapper
|
601
|
-
|
602
|
-
|
603
|
-
class _DefaultLifespan:
|
604
|
-
def __init__(self, router: "Router"):
|
605
|
-
self._router = router
|
606
|
-
|
607
|
-
async def __aenter__(self) -> None:
|
608
|
-
await self._router.startup()
|
609
|
-
|
610
|
-
async def __aexit__(self, *exc_info: object) -> None:
|
611
|
-
await self._router.shutdown()
|
612
|
-
|
613
|
-
def __call__(self: _T, app: object) -> _T:
|
614
|
-
return self
|
615
|
-
|
616
|
-
|
617
|
-
class Router:
|
618
|
-
def __init__(
|
619
|
-
self,
|
620
|
-
routes: typing.Optional[typing.Sequence[BaseRoute]] = None,
|
621
|
-
redirect_slashes: bool = True,
|
622
|
-
default: typing.Optional[ASGIApp] = None,
|
623
|
-
on_startup: typing.Optional[
|
624
|
-
typing.Sequence[typing.Callable[[], typing.Any]]
|
625
|
-
] = None,
|
626
|
-
on_shutdown: typing.Optional[
|
627
|
-
typing.Sequence[typing.Callable[[], typing.Any]]
|
628
|
-
] = None,
|
629
|
-
# the generic to Lifespan[AppType] is the type of the top level application
|
630
|
-
# which the router cannot know statically, so we use typing.Any
|
631
|
-
lifespan: typing.Optional[Lifespan[typing.Any]] = None,
|
632
|
-
*,
|
633
|
-
middleware: typing.Optional[typing.Sequence[Middleware]] = None,
|
634
|
-
) -> None:
|
635
|
-
self.routes = [] if routes is None else list(routes)
|
636
|
-
self.redirect_slashes = redirect_slashes
|
637
|
-
self.default = self.not_found if default is None else default
|
638
|
-
self.on_startup = [] if on_startup is None else list(on_startup)
|
639
|
-
self.on_shutdown = [] if on_shutdown is None else list(on_shutdown)
|
640
|
-
|
641
|
-
if on_startup or on_shutdown:
|
642
|
-
warnings.warn(
|
643
|
-
"The on_startup and on_shutdown parameters are deprecated, and they "
|
644
|
-
"will be removed on version 1.0. Use the lifespan parameter instead. "
|
645
|
-
"See more about it on https://www.starlette.io/lifespan/.",
|
646
|
-
DeprecationWarning,
|
647
|
-
)
|
648
|
-
if lifespan:
|
649
|
-
warnings.warn(
|
650
|
-
"The `lifespan` parameter cannot be used with `on_startup` or "
|
651
|
-
"`on_shutdown`. Both `on_startup` and `on_shutdown` will be "
|
652
|
-
"ignored."
|
653
|
-
)
|
654
|
-
|
655
|
-
if lifespan is None:
|
656
|
-
self.lifespan_context: Lifespan[typing.Any] = _DefaultLifespan(self)
|
657
|
-
|
658
|
-
elif inspect.isasyncgenfunction(lifespan):
|
659
|
-
warnings.warn(
|
660
|
-
"async generator function lifespans are deprecated, "
|
661
|
-
"use an @contextlib.asynccontextmanager function instead",
|
662
|
-
DeprecationWarning,
|
663
|
-
)
|
664
|
-
self.lifespan_context = asynccontextmanager(
|
665
|
-
lifespan,
|
666
|
-
)
|
667
|
-
elif inspect.isgeneratorfunction(lifespan):
|
668
|
-
warnings.warn(
|
669
|
-
"generator function lifespans are deprecated, "
|
670
|
-
"use an @contextlib.asynccontextmanager function instead",
|
671
|
-
DeprecationWarning,
|
672
|
-
)
|
673
|
-
self.lifespan_context = _wrap_gen_lifespan_context(
|
674
|
-
lifespan,
|
675
|
-
)
|
676
|
-
else:
|
677
|
-
self.lifespan_context = lifespan
|
678
|
-
|
679
|
-
self.middleware_stack = self.app
|
680
|
-
if middleware:
|
681
|
-
for cls, options in reversed(middleware):
|
682
|
-
self.middleware_stack = cls(self.middleware_stack, **options)
|
683
|
-
|
684
|
-
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:
|
685
|
-
if scope["type"] == "websocket":
|
686
|
-
websocket_close = WebSocketClose()
|
687
|
-
await websocket_close(scope, receive, send)
|
688
|
-
return
|
689
|
-
|
690
|
-
# If we're running inside a starlette application then raise an
|
691
|
-
# exception, so that the configurable exception handler can deal with
|
692
|
-
# returning the response. For plain ASGI apps, just return the response.
|
693
|
-
if "app" in scope:
|
694
|
-
raise HTTPException(status_code=404)
|
695
|
-
else:
|
696
|
-
response = PlainTextResponse("Not Found", status_code=404)
|
697
|
-
await response(scope, receive, send)
|
698
|
-
|
699
|
-
def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
|
700
|
-
for route in self.routes:
|
701
|
-
try:
|
702
|
-
return route.url_path_for(name, **path_params)
|
703
|
-
except NoMatchFound:
|
704
|
-
pass
|
705
|
-
raise NoMatchFound(name, path_params)
|
706
|
-
|
707
|
-
async def startup(self) -> None:
|
708
|
-
"""
|
709
|
-
Run any `.on_startup` event handlers.
|
710
|
-
"""
|
711
|
-
for handler in self.on_startup:
|
712
|
-
if is_async_callable(handler):
|
713
|
-
await handler()
|
714
|
-
else:
|
715
|
-
handler()
|
716
|
-
|
717
|
-
async def shutdown(self) -> None:
|
718
|
-
"""
|
719
|
-
Run any `.on_shutdown` event handlers.
|
720
|
-
"""
|
721
|
-
for handler in self.on_shutdown:
|
722
|
-
if is_async_callable(handler):
|
723
|
-
await handler()
|
724
|
-
else:
|
725
|
-
handler()
|
726
|
-
|
727
|
-
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:
|
728
|
-
"""
|
729
|
-
Handle ASGI lifespan messages, which allows us to manage application
|
730
|
-
startup and shutdown events.
|
731
|
-
"""
|
732
|
-
started = False
|
733
|
-
app: typing.Any = scope.get("app")
|
734
|
-
await receive()
|
735
|
-
try:
|
736
|
-
async with self.lifespan_context(app) as maybe_state:
|
737
|
-
if maybe_state is not None:
|
738
|
-
if "state" not in scope:
|
739
|
-
raise RuntimeError(
|
740
|
-
'The server does not support "state" in the lifespan scope.'
|
741
|
-
)
|
742
|
-
scope["state"].update(maybe_state)
|
743
|
-
await send({"type": "lifespan.startup.complete"})
|
744
|
-
started = True
|
745
|
-
await receive()
|
746
|
-
except BaseException:
|
747
|
-
exc_text = traceback.format_exc()
|
748
|
-
if started:
|
749
|
-
await send({"type": "lifespan.shutdown.failed", "message": exc_text})
|
750
|
-
else:
|
751
|
-
await send({"type": "lifespan.startup.failed", "message": exc_text})
|
752
|
-
raise
|
753
|
-
else:
|
754
|
-
await send({"type": "lifespan.shutdown.complete"})
|
755
|
-
|
756
|
-
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
757
|
-
"""
|
758
|
-
The main entry point to the Router class.
|
759
|
-
"""
|
760
|
-
await self.middleware_stack(scope, receive, send)
|
761
|
-
|
762
|
-
async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
|
763
|
-
assert scope["type"] in ("http", "websocket", "lifespan")
|
764
|
-
|
765
|
-
if "router" not in scope:
|
766
|
-
scope["router"] = self
|
767
|
-
|
768
|
-
if scope["type"] == "lifespan":
|
769
|
-
await self.lifespan(scope, receive, send)
|
770
|
-
return
|
771
|
-
|
772
|
-
partial = None
|
773
|
-
|
774
|
-
for route in self.routes:
|
775
|
-
# Determine if any route matches the incoming scope,
|
776
|
-
# and hand over to the matching route if found.
|
777
|
-
match, child_scope = route.matches(scope)
|
778
|
-
if match == Match.FULL:
|
779
|
-
scope.update(child_scope)
|
780
|
-
await route.handle(scope, receive, send)
|
781
|
-
return
|
782
|
-
elif match == Match.PARTIAL and partial is None:
|
783
|
-
partial = route
|
784
|
-
partial_scope = child_scope
|
785
|
-
|
786
|
-
if partial is not None:
|
787
|
-
# Handle partial matches. These are cases where an endpoint is
|
788
|
-
# able to handle the request, but is not a preferred option.
|
789
|
-
# We use this in particular to deal with "405 Method Not Allowed".
|
790
|
-
scope.update(partial_scope)
|
791
|
-
await partial.handle(scope, receive, send)
|
792
|
-
return
|
793
|
-
|
794
|
-
root_path = scope.get("route_root_path", scope.get("root_path", ""))
|
795
|
-
path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"]))
|
796
|
-
if scope["type"] == "http" and self.redirect_slashes and path != "/":
|
797
|
-
redirect_scope = dict(scope)
|
798
|
-
if path.endswith("/"):
|
799
|
-
redirect_scope["route_path"] = path.rstrip("/")
|
800
|
-
redirect_scope["path"] = redirect_scope["path"].rstrip("/")
|
801
|
-
else:
|
802
|
-
redirect_scope["route_path"] = path + "/"
|
803
|
-
redirect_scope["path"] = redirect_scope["path"] + "/"
|
804
|
-
|
805
|
-
for route in self.routes:
|
806
|
-
match, child_scope = route.matches(redirect_scope)
|
807
|
-
if match != Match.NONE:
|
808
|
-
redirect_url = URL(scope=redirect_scope)
|
809
|
-
response = RedirectResponse(url=str(redirect_url))
|
810
|
-
await response(scope, receive, send)
|
811
|
-
return
|
812
|
-
|
813
|
-
await self.default(scope, receive, send)
|
814
|
-
|
815
|
-
def __eq__(self, other: typing.Any) -> bool:
|
816
|
-
return isinstance(other, Router) and self.routes == other.routes
|
817
|
-
|
818
|
-
def mount(
|
819
|
-
self, path: str, app: ASGIApp, name: typing.Optional[str] = None
|
820
|
-
) -> None: # pragma: nocover
|
821
|
-
route = Mount(path, app=app, name=name)
|
822
|
-
self.routes.append(route)
|
823
|
-
|
824
|
-
def host(
|
825
|
-
self, host: str, app: ASGIApp, name: typing.Optional[str] = None
|
826
|
-
) -> None: # pragma: no cover
|
827
|
-
route = Host(host, app=app, name=name)
|
828
|
-
self.routes.append(route)
|
829
|
-
|
830
|
-
def add_route(
|
831
|
-
self,
|
832
|
-
path: str,
|
833
|
-
endpoint: typing.Callable[
|
834
|
-
[Request], typing.Union[typing.Awaitable[Response], Response]
|
835
|
-
],
|
836
|
-
methods: typing.Optional[typing.List[str]] = None,
|
837
|
-
name: typing.Optional[str] = None,
|
838
|
-
include_in_schema: bool = True,
|
839
|
-
) -> None: # pragma: nocover
|
840
|
-
route = Route(
|
841
|
-
path,
|
842
|
-
endpoint=endpoint,
|
843
|
-
methods=methods,
|
844
|
-
name=name,
|
845
|
-
include_in_schema=include_in_schema,
|
846
|
-
)
|
847
|
-
self.routes.append(route)
|
848
|
-
|
849
|
-
def add_websocket_route(
|
850
|
-
self,
|
851
|
-
path: str,
|
852
|
-
endpoint: typing.Callable[[WebSocket], typing.Awaitable[None]],
|
853
|
-
name: typing.Optional[str] = None,
|
854
|
-
) -> None: # pragma: no cover
|
855
|
-
route = WebSocketRoute(path, endpoint=endpoint, name=name)
|
856
|
-
self.routes.append(route)
|
857
|
-
|
858
|
-
def route(
|
859
|
-
self,
|
860
|
-
path: str,
|
861
|
-
methods: typing.Optional[typing.List[str]] = None,
|
862
|
-
name: typing.Optional[str] = None,
|
863
|
-
include_in_schema: bool = True,
|
864
|
-
) -> typing.Callable: # type: ignore[type-arg]
|
865
|
-
"""
|
866
|
-
We no longer document this decorator style API, and its usage is discouraged.
|
867
|
-
Instead you should use the following approach:
|
868
|
-
|
869
|
-
>>> routes = [Route(path, endpoint=...), ...]
|
870
|
-
>>> app = Starlette(routes=routes)
|
871
|
-
"""
|
872
|
-
warnings.warn(
|
873
|
-
"The `route` decorator is deprecated, and will be removed in version 1.0.0."
|
874
|
-
"Refer to https://www.starlette.io/routing/#http-routing for the recommended approach.", # noqa: E501
|
875
|
-
DeprecationWarning,
|
876
|
-
)
|
877
|
-
|
878
|
-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
|
879
|
-
self.add_route(
|
880
|
-
path,
|
881
|
-
func,
|
882
|
-
methods=methods,
|
883
|
-
name=name,
|
884
|
-
include_in_schema=include_in_schema,
|
885
|
-
)
|
886
|
-
return func
|
887
|
-
|
888
|
-
return decorator
|
889
|
-
|
890
|
-
def websocket_route(
|
891
|
-
self, path: str, name: typing.Optional[str] = None
|
892
|
-
) -> typing.Callable: # type: ignore[type-arg]
|
893
|
-
"""
|
894
|
-
We no longer document this decorator style API, and its usage is discouraged.
|
895
|
-
Instead you should use the following approach:
|
896
|
-
|
897
|
-
>>> routes = [WebSocketRoute(path, endpoint=...), ...]
|
898
|
-
>>> app = Starlette(routes=routes)
|
899
|
-
"""
|
900
|
-
warnings.warn(
|
901
|
-
"The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. Refer to " # noqa: E501
|
902
|
-
"https://www.starlette.io/routing/#websocket-routing for the recommended approach.", # noqa: E501
|
903
|
-
DeprecationWarning,
|
904
|
-
)
|
905
|
-
|
906
|
-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
|
907
|
-
self.add_websocket_route(path, func, name=name)
|
908
|
-
return func
|
909
|
-
|
910
|
-
return decorator
|
911
|
-
|
912
|
-
def add_event_handler(
|
913
|
-
self, event_type: str, func: typing.Callable[[], typing.Any]
|
914
|
-
) -> None: # pragma: no cover
|
915
|
-
assert event_type in ("startup", "shutdown")
|
916
|
-
|
917
|
-
if event_type == "startup":
|
918
|
-
self.on_startup.append(func)
|
919
|
-
else:
|
920
|
-
self.on_shutdown.append(func)
|
921
|
-
|
922
|
-
def on_event(self, event_type: str) -> typing.Callable: # type: ignore[type-arg]
|
923
|
-
warnings.warn(
|
924
|
-
"The `on_event` decorator is deprecated, and will be removed in version 1.0.0. " # noqa: E501
|
925
|
-
"Refer to https://www.starlette.io/lifespan/ for recommended approach.",
|
926
|
-
DeprecationWarning,
|
927
|
-
)
|
928
|
-
|
929
|
-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
|
930
|
-
self.add_event_handler(event_type, func)
|
931
|
-
return func
|
932
|
-
|
933
|
-
return decorator
|