prefect-client 2.19.2__py3-none-any.whl → 3.0.0rc1__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.
Files changed (239) hide show
  1. prefect/__init__.py +8 -56
  2. prefect/_internal/compatibility/deprecated.py +6 -115
  3. prefect/_internal/compatibility/experimental.py +4 -79
  4. prefect/_internal/concurrency/api.py +0 -34
  5. prefect/_internal/concurrency/calls.py +0 -6
  6. prefect/_internal/concurrency/cancellation.py +0 -3
  7. prefect/_internal/concurrency/event_loop.py +0 -20
  8. prefect/_internal/concurrency/inspection.py +3 -3
  9. prefect/_internal/concurrency/threads.py +35 -0
  10. prefect/_internal/concurrency/waiters.py +0 -28
  11. prefect/_internal/pydantic/__init__.py +0 -45
  12. prefect/_internal/pydantic/v1_schema.py +21 -22
  13. prefect/_internal/pydantic/v2_schema.py +0 -2
  14. prefect/_internal/pydantic/v2_validated_func.py +18 -23
  15. prefect/_internal/schemas/bases.py +44 -177
  16. prefect/_internal/schemas/fields.py +1 -43
  17. prefect/_internal/schemas/validators.py +60 -158
  18. prefect/artifacts.py +161 -14
  19. prefect/automations.py +39 -4
  20. prefect/blocks/abstract.py +1 -1
  21. prefect/blocks/core.py +268 -148
  22. prefect/blocks/fields.py +2 -57
  23. prefect/blocks/kubernetes.py +8 -12
  24. prefect/blocks/notifications.py +40 -20
  25. prefect/blocks/system.py +22 -11
  26. prefect/blocks/webhook.py +2 -9
  27. prefect/client/base.py +4 -4
  28. prefect/client/cloud.py +8 -13
  29. prefect/client/orchestration.py +347 -341
  30. prefect/client/schemas/actions.py +92 -86
  31. prefect/client/schemas/filters.py +20 -40
  32. prefect/client/schemas/objects.py +151 -145
  33. prefect/client/schemas/responses.py +16 -24
  34. prefect/client/schemas/schedules.py +47 -35
  35. prefect/client/subscriptions.py +2 -2
  36. prefect/client/utilities.py +5 -2
  37. prefect/concurrency/asyncio.py +3 -1
  38. prefect/concurrency/events.py +1 -1
  39. prefect/concurrency/services.py +6 -3
  40. prefect/context.py +195 -27
  41. prefect/deployments/__init__.py +5 -6
  42. prefect/deployments/base.py +7 -5
  43. prefect/deployments/flow_runs.py +185 -0
  44. prefect/deployments/runner.py +50 -45
  45. prefect/deployments/schedules.py +28 -23
  46. prefect/deployments/steps/__init__.py +0 -1
  47. prefect/deployments/steps/core.py +1 -0
  48. prefect/deployments/steps/pull.py +7 -21
  49. prefect/engine.py +12 -2422
  50. prefect/events/actions.py +17 -23
  51. prefect/events/cli/automations.py +19 -6
  52. prefect/events/clients.py +14 -37
  53. prefect/events/filters.py +14 -18
  54. prefect/events/related.py +2 -2
  55. prefect/events/schemas/__init__.py +0 -5
  56. prefect/events/schemas/automations.py +55 -46
  57. prefect/events/schemas/deployment_triggers.py +7 -197
  58. prefect/events/schemas/events.py +34 -65
  59. prefect/events/schemas/labelling.py +10 -14
  60. prefect/events/utilities.py +2 -3
  61. prefect/events/worker.py +2 -3
  62. prefect/filesystems.py +6 -517
  63. prefect/{new_flow_engine.py → flow_engine.py} +313 -72
  64. prefect/flow_runs.py +377 -5
  65. prefect/flows.py +307 -166
  66. prefect/futures.py +186 -345
  67. prefect/infrastructure/__init__.py +0 -27
  68. prefect/infrastructure/provisioners/__init__.py +5 -3
  69. prefect/infrastructure/provisioners/cloud_run.py +11 -6
  70. prefect/infrastructure/provisioners/container_instance.py +11 -7
  71. prefect/infrastructure/provisioners/ecs.py +6 -4
  72. prefect/infrastructure/provisioners/modal.py +8 -5
  73. prefect/input/actions.py +2 -4
  74. prefect/input/run_input.py +5 -7
  75. prefect/logging/formatters.py +0 -2
  76. prefect/logging/handlers.py +3 -11
  77. prefect/logging/loggers.py +2 -2
  78. prefect/manifests.py +2 -1
  79. prefect/records/__init__.py +1 -0
  80. prefect/records/result_store.py +42 -0
  81. prefect/records/store.py +9 -0
  82. prefect/results.py +43 -39
  83. prefect/runner/runner.py +19 -15
  84. prefect/runner/server.py +6 -10
  85. prefect/runner/storage.py +3 -8
  86. prefect/runner/submit.py +2 -2
  87. prefect/runner/utils.py +2 -2
  88. prefect/serializers.py +24 -35
  89. prefect/server/api/collections_data/views/aggregate-worker-metadata.json +5 -14
  90. prefect/settings.py +70 -133
  91. prefect/states.py +17 -47
  92. prefect/task_engine.py +697 -58
  93. prefect/task_runners.py +269 -301
  94. prefect/task_server.py +53 -34
  95. prefect/tasks.py +327 -337
  96. prefect/transactions.py +220 -0
  97. prefect/types/__init__.py +61 -82
  98. prefect/utilities/asyncutils.py +195 -136
  99. prefect/utilities/callables.py +311 -43
  100. prefect/utilities/collections.py +23 -38
  101. prefect/utilities/dispatch.py +11 -3
  102. prefect/utilities/dockerutils.py +4 -0
  103. prefect/utilities/engine.py +140 -20
  104. prefect/utilities/importtools.py +97 -27
  105. prefect/utilities/pydantic.py +128 -38
  106. prefect/utilities/schema_tools/hydration.py +5 -1
  107. prefect/utilities/templating.py +12 -2
  108. prefect/variables.py +78 -61
  109. prefect/workers/__init__.py +0 -1
  110. prefect/workers/base.py +15 -17
  111. prefect/workers/process.py +3 -8
  112. prefect/workers/server.py +2 -2
  113. {prefect_client-2.19.2.dist-info → prefect_client-3.0.0rc1.dist-info}/METADATA +22 -21
  114. prefect_client-3.0.0rc1.dist-info/RECORD +176 -0
  115. prefect/_internal/pydantic/_base_model.py +0 -51
  116. prefect/_internal/pydantic/_compat.py +0 -82
  117. prefect/_internal/pydantic/_flags.py +0 -20
  118. prefect/_internal/pydantic/_types.py +0 -8
  119. prefect/_internal/pydantic/utilities/__init__.py +0 -0
  120. prefect/_internal/pydantic/utilities/config_dict.py +0 -72
  121. prefect/_internal/pydantic/utilities/field_validator.py +0 -150
  122. prefect/_internal/pydantic/utilities/model_construct.py +0 -56
  123. prefect/_internal/pydantic/utilities/model_copy.py +0 -55
  124. prefect/_internal/pydantic/utilities/model_dump.py +0 -136
  125. prefect/_internal/pydantic/utilities/model_dump_json.py +0 -112
  126. prefect/_internal/pydantic/utilities/model_fields.py +0 -50
  127. prefect/_internal/pydantic/utilities/model_fields_set.py +0 -29
  128. prefect/_internal/pydantic/utilities/model_json_schema.py +0 -82
  129. prefect/_internal/pydantic/utilities/model_rebuild.py +0 -80
  130. prefect/_internal/pydantic/utilities/model_validate.py +0 -75
  131. prefect/_internal/pydantic/utilities/model_validate_json.py +0 -68
  132. prefect/_internal/pydantic/utilities/model_validator.py +0 -87
  133. prefect/_internal/pydantic/utilities/type_adapter.py +0 -71
  134. prefect/_vendor/__init__.py +0 -0
  135. prefect/_vendor/fastapi/__init__.py +0 -25
  136. prefect/_vendor/fastapi/applications.py +0 -946
  137. prefect/_vendor/fastapi/background.py +0 -3
  138. prefect/_vendor/fastapi/concurrency.py +0 -44
  139. prefect/_vendor/fastapi/datastructures.py +0 -58
  140. prefect/_vendor/fastapi/dependencies/__init__.py +0 -0
  141. prefect/_vendor/fastapi/dependencies/models.py +0 -64
  142. prefect/_vendor/fastapi/dependencies/utils.py +0 -877
  143. prefect/_vendor/fastapi/encoders.py +0 -177
  144. prefect/_vendor/fastapi/exception_handlers.py +0 -40
  145. prefect/_vendor/fastapi/exceptions.py +0 -46
  146. prefect/_vendor/fastapi/logger.py +0 -3
  147. prefect/_vendor/fastapi/middleware/__init__.py +0 -1
  148. prefect/_vendor/fastapi/middleware/asyncexitstack.py +0 -25
  149. prefect/_vendor/fastapi/middleware/cors.py +0 -3
  150. prefect/_vendor/fastapi/middleware/gzip.py +0 -3
  151. prefect/_vendor/fastapi/middleware/httpsredirect.py +0 -3
  152. prefect/_vendor/fastapi/middleware/trustedhost.py +0 -3
  153. prefect/_vendor/fastapi/middleware/wsgi.py +0 -3
  154. prefect/_vendor/fastapi/openapi/__init__.py +0 -0
  155. prefect/_vendor/fastapi/openapi/constants.py +0 -2
  156. prefect/_vendor/fastapi/openapi/docs.py +0 -203
  157. prefect/_vendor/fastapi/openapi/models.py +0 -480
  158. prefect/_vendor/fastapi/openapi/utils.py +0 -485
  159. prefect/_vendor/fastapi/param_functions.py +0 -340
  160. prefect/_vendor/fastapi/params.py +0 -453
  161. prefect/_vendor/fastapi/requests.py +0 -4
  162. prefect/_vendor/fastapi/responses.py +0 -40
  163. prefect/_vendor/fastapi/routing.py +0 -1331
  164. prefect/_vendor/fastapi/security/__init__.py +0 -15
  165. prefect/_vendor/fastapi/security/api_key.py +0 -98
  166. prefect/_vendor/fastapi/security/base.py +0 -6
  167. prefect/_vendor/fastapi/security/http.py +0 -172
  168. prefect/_vendor/fastapi/security/oauth2.py +0 -227
  169. prefect/_vendor/fastapi/security/open_id_connect_url.py +0 -34
  170. prefect/_vendor/fastapi/security/utils.py +0 -10
  171. prefect/_vendor/fastapi/staticfiles.py +0 -1
  172. prefect/_vendor/fastapi/templating.py +0 -3
  173. prefect/_vendor/fastapi/testclient.py +0 -1
  174. prefect/_vendor/fastapi/types.py +0 -3
  175. prefect/_vendor/fastapi/utils.py +0 -235
  176. prefect/_vendor/fastapi/websockets.py +0 -7
  177. prefect/_vendor/starlette/__init__.py +0 -1
  178. prefect/_vendor/starlette/_compat.py +0 -28
  179. prefect/_vendor/starlette/_exception_handler.py +0 -80
  180. prefect/_vendor/starlette/_utils.py +0 -88
  181. prefect/_vendor/starlette/applications.py +0 -261
  182. prefect/_vendor/starlette/authentication.py +0 -159
  183. prefect/_vendor/starlette/background.py +0 -43
  184. prefect/_vendor/starlette/concurrency.py +0 -59
  185. prefect/_vendor/starlette/config.py +0 -151
  186. prefect/_vendor/starlette/convertors.py +0 -87
  187. prefect/_vendor/starlette/datastructures.py +0 -707
  188. prefect/_vendor/starlette/endpoints.py +0 -130
  189. prefect/_vendor/starlette/exceptions.py +0 -60
  190. prefect/_vendor/starlette/formparsers.py +0 -276
  191. prefect/_vendor/starlette/middleware/__init__.py +0 -17
  192. prefect/_vendor/starlette/middleware/authentication.py +0 -52
  193. prefect/_vendor/starlette/middleware/base.py +0 -220
  194. prefect/_vendor/starlette/middleware/cors.py +0 -176
  195. prefect/_vendor/starlette/middleware/errors.py +0 -265
  196. prefect/_vendor/starlette/middleware/exceptions.py +0 -74
  197. prefect/_vendor/starlette/middleware/gzip.py +0 -113
  198. prefect/_vendor/starlette/middleware/httpsredirect.py +0 -19
  199. prefect/_vendor/starlette/middleware/sessions.py +0 -82
  200. prefect/_vendor/starlette/middleware/trustedhost.py +0 -64
  201. prefect/_vendor/starlette/middleware/wsgi.py +0 -147
  202. prefect/_vendor/starlette/requests.py +0 -328
  203. prefect/_vendor/starlette/responses.py +0 -347
  204. prefect/_vendor/starlette/routing.py +0 -933
  205. prefect/_vendor/starlette/schemas.py +0 -154
  206. prefect/_vendor/starlette/staticfiles.py +0 -248
  207. prefect/_vendor/starlette/status.py +0 -199
  208. prefect/_vendor/starlette/templating.py +0 -231
  209. prefect/_vendor/starlette/testclient.py +0 -804
  210. prefect/_vendor/starlette/types.py +0 -30
  211. prefect/_vendor/starlette/websockets.py +0 -193
  212. prefect/agent.py +0 -698
  213. prefect/deployments/deployments.py +0 -1042
  214. prefect/deprecated/__init__.py +0 -0
  215. prefect/deprecated/data_documents.py +0 -350
  216. prefect/deprecated/packaging/__init__.py +0 -12
  217. prefect/deprecated/packaging/base.py +0 -96
  218. prefect/deprecated/packaging/docker.py +0 -146
  219. prefect/deprecated/packaging/file.py +0 -92
  220. prefect/deprecated/packaging/orion.py +0 -80
  221. prefect/deprecated/packaging/serializers.py +0 -171
  222. prefect/events/instrument.py +0 -135
  223. prefect/infrastructure/base.py +0 -323
  224. prefect/infrastructure/container.py +0 -818
  225. prefect/infrastructure/kubernetes.py +0 -920
  226. prefect/infrastructure/process.py +0 -289
  227. prefect/new_task_engine.py +0 -423
  228. prefect/pydantic/__init__.py +0 -76
  229. prefect/pydantic/main.py +0 -39
  230. prefect/software/__init__.py +0 -2
  231. prefect/software/base.py +0 -50
  232. prefect/software/conda.py +0 -199
  233. prefect/software/pip.py +0 -122
  234. prefect/software/python.py +0 -52
  235. prefect/workers/block.py +0 -218
  236. prefect_client-2.19.2.dist-info/RECORD +0 -292
  237. {prefect_client-2.19.2.dist-info → prefect_client-3.0.0rc1.dist-info}/LICENSE +0 -0
  238. {prefect_client-2.19.2.dist-info → prefect_client-3.0.0rc1.dist-info}/WHEEL +0 -0
  239. {prefect_client-2.19.2.dist-info → prefect_client-3.0.0rc1.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