asgi-tools 3.2.2__tar.gz → 3.3.0__tar.gz

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 (44) hide show
  1. {asgi_tools-3.2.2/asgi_tools.egg-info → asgi_tools-3.3.0}/PKG-INFO +1 -1
  2. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/_compat.py +42 -37
  3. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/app.py +19 -13
  4. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/forms.py +29 -22
  5. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/middleware.py +34 -28
  6. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/multipart.py +12 -10
  7. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/request.py +10 -10
  8. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/response.py +46 -28
  9. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/router.py +2 -2
  10. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/tests.py +39 -31
  11. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/types.py +3 -3
  12. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/utils.py +5 -5
  13. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/view.py +7 -5
  14. {asgi_tools-3.2.2 → asgi_tools-3.3.0/asgi_tools.egg-info}/PKG-INFO +1 -1
  15. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/pyproject.toml +9 -2
  16. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/LICENSE +0 -0
  17. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/MANIFEST.in +0 -0
  18. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/README.md +0 -0
  19. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/__init__.py +0 -0
  20. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/constants.py +0 -0
  21. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/errors.py +0 -0
  22. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/forms.pyx +0 -0
  23. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/logs.py +0 -0
  24. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/multipart.pxd +0 -0
  25. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/multipart.pyx +0 -0
  26. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools/py.typed +0 -0
  27. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools.egg-info/SOURCES.txt +0 -0
  28. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools.egg-info/dependency_links.txt +0 -0
  29. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools.egg-info/requires.txt +0 -0
  30. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/asgi_tools.egg-info/top_level.txt +0 -0
  31. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/setup.cfg +0 -0
  32. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/setup.py +0 -0
  33. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_app.py +0 -0
  34. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_benchmarks.py +0 -0
  35. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_client.py +0 -0
  36. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_compat.py +0 -0
  37. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_compatibility.py +0 -0
  38. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_examples.py +0 -0
  39. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_formdata.py +0 -0
  40. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_middlewares.py +0 -0
  41. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_request.py +0 -0
  42. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_responses.py +0 -0
  43. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_types.py +0 -0
  44. {asgi_tools-3.2.2 → asgi_tools-3.3.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: asgi-tools
3
- Version: 3.2.2
3
+ Version: 3.3.0
4
4
  Summary: ASGI Toolkit to build web applications
5
5
  Author-email: Kirill Klenov <horneds@gmail.com>
6
6
  License: MIT License
@@ -6,7 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import asyncio
8
8
  import inspect
9
- from asyncio import create_task, gather, sleep
9
+ from asyncio import create_task, ensure_future, gather, sleep
10
10
  from concurrent.futures import ALL_COMPLETED, FIRST_COMPLETED
11
11
  from contextlib import asynccontextmanager, suppress
12
12
  from typing import (
@@ -74,40 +74,42 @@ with suppress(ImportError):
74
74
  curio_installed = True
75
75
 
76
76
 
77
- def aio_sleep(seconds: float = 0) -> Awaitable:
77
+ def aio_sleep(seconds: float = 0) -> Awaitable[Any]:
78
78
  """Return sleep coroutine."""
79
79
 
80
80
  if trio_installed and current_async_library() == "trio":
81
- return trio_sleep(seconds) # noqa: ASYNC105 # type: ignore[]
81
+ return cast("Awaitable[Any]", trio_sleep(seconds)) # noqa: ASYNC105
82
82
 
83
83
  if curio_installed and current_async_library() == "curio":
84
- return curio_sleep(seconds) # type: ignore[]
84
+ return cast("Awaitable[Any]", curio_sleep(seconds))
85
85
 
86
86
  return sleep(seconds)
87
87
 
88
88
 
89
89
  @asynccontextmanager
90
- async def aio_spawn(fn: Callable[..., Awaitable], *args, **kwargs):
90
+ async def aio_spawn(
91
+ fn: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any
92
+ ) -> AsyncGenerator[Any, None]:
91
93
  """Spawn a given coroutine."""
92
94
  if trio_installed and current_async_library() == "trio":
93
- async with open_nursery() as tasks: # type: ignore[]
95
+ async with open_nursery() as tasks:
94
96
  tasks.start_soon(fn, *args, **kwargs)
95
97
  yield tasks
96
98
 
97
99
  elif curio_installed and current_async_library() == "curio":
98
- task = await curio_spawn(fn, *args, **kwargs) # type: ignore[]
100
+ task = await curio_spawn(fn, *args, **kwargs)
99
101
  yield task
100
- await task.join() # type: ignore [union-attr]
102
+ await task.join()
101
103
 
102
104
  else:
103
- coro = cast("Coroutine", fn(*args, **kwargs))
105
+ coro = cast("Coroutine[Any, Any, Any]", fn(*args, **kwargs))
104
106
  task = create_task(coro)
105
107
  yield task
106
108
  await task
107
109
 
108
110
 
109
111
  @asynccontextmanager
110
- async def aio_timeout(timeout: float):
112
+ async def aio_timeout(timeout: float) -> AsyncGenerator[None, None]:
111
113
  """Fail after the given timeout."""
112
114
  if not timeout:
113
115
  yield
@@ -115,18 +117,18 @@ async def aio_timeout(timeout: float):
115
117
 
116
118
  if trio_installed and current_async_library() == "trio":
117
119
  try:
118
- with trio_fail_after(timeout): # type: ignore[]
120
+ with trio_fail_after(timeout):
119
121
  yield
120
122
 
121
- except TooSlowError: # type: ignore[]
123
+ except TooSlowError:
122
124
  raise TimeoutError(f"{timeout}s.") from None
123
125
 
124
126
  elif curio_installed and current_async_library() == "curio":
125
127
  try:
126
- async with curio_fail_after(timeout): # type: ignore[]
128
+ async with curio_fail_after(timeout):
127
129
  yield
128
130
 
129
- except TaskTimeout: # type: ignore[]
131
+ except TaskTimeout:
130
132
  raise TimeoutError(f"{timeout}s.") from None
131
133
 
132
134
  else:
@@ -134,7 +136,7 @@ async def aio_timeout(timeout: float):
134
136
  yield
135
137
 
136
138
 
137
- async def aio_wait(*aws: Awaitable, strategy: str = ALL_COMPLETED) -> Any:
139
+ async def aio_wait(*aws: Awaitable[Any], strategy: str = ALL_COMPLETED) -> Any:
138
140
  """Run the coros concurrently, wait for all completed or cancel others.
139
141
 
140
142
  Only ALL_COMPLETED, FIRST_COMPLETED are supported.
@@ -143,9 +145,9 @@ async def aio_wait(*aws: Awaitable, strategy: str = ALL_COMPLETED) -> Any:
143
145
  return None
144
146
 
145
147
  if trio_installed and current_async_library() == "trio":
146
- send_channel, receive_channel = open_memory_channel(0) # type: ignore[var-annotated]
148
+ send_channel, receive_channel = open_memory_channel(0)
147
149
 
148
- async with open_nursery() as n: # type: ignore[]
150
+ async with open_nursery() as n:
149
151
  for aw in aws:
150
152
  n.start_soon(trio_jockey, aw, send_channel)
151
153
 
@@ -165,28 +167,29 @@ async def aio_wait(*aws: Awaitable, strategy: str = ALL_COMPLETED) -> Any:
165
167
 
166
168
  return g.results if strategy == ALL_COMPLETED else g.result
167
169
 
168
- aws = tuple(create_task(aw) if inspect.iscoroutine(aw) else aw for aw in aws)
169
- done, pending = await asyncio.wait(aws, return_when=strategy) # type: ignore[type-var]
170
+ tasks = tuple(create_task(aw) if inspect.iscoroutine(aw) else ensure_future(aw) for aw in aws)
171
+ done, pending = await asyncio.wait(tasks, return_when=strategy)
170
172
  if strategy != ALL_COMPLETED:
171
173
  for task in pending:
172
- task.cancel() # type: ignore[attr-defined]
174
+ task.cancel()
173
175
  await gather(*pending, return_exceptions=True)
174
- return next(iter(done)).result() # type: ignore[attr-defined]
176
+ return next(iter(done)).result()
175
177
 
176
- return [t.result() for t in done] # type: ignore[attr-defined]
178
+ return [t.result() for t in done]
177
179
 
178
180
 
179
- async def aio_cancel(task):
181
+ async def aio_cancel(task: Any) -> None:
180
182
  """Cancel asyncio task / trio nursery."""
181
183
  if isinstance(task, asyncio.Task):
182
- return task.cancel()
184
+ task.cancel()
185
+ return
183
186
 
184
187
  if trio_installed and current_async_library() == "trio":
185
- return task.cancel_scope.cancel()
188
+ task.cancel_scope.cancel()
189
+ return
186
190
 
187
191
  if curio_installed and current_async_library() == "curio":
188
- return await task.cancel()
189
- return None
192
+ await task.cancel()
190
193
 
191
194
 
192
195
  async def aio_stream_file(
@@ -215,20 +218,18 @@ async def aio_stream_file(
215
218
  )
216
219
 
217
220
  async with aiofile.AIOFile(filepath, mode="rb") as fp:
218
- async for chunk in aiofile.Reader( # type: ignore [assignment]
219
- fp, chunk_size=chunk_size
220
- ):
221
- yield cast("bytes", chunk)
221
+ async for data in aiofile.Reader(fp, chunk_size=chunk_size):
222
+ yield cast("bytes", data)
222
223
 
223
224
 
224
- async def trio_jockey(coro: Awaitable, channel):
225
+ async def trio_jockey(coro: Awaitable[Any], channel: Any) -> None:
225
226
  """Wait for the given coroutine and send result back to the given channel."""
226
227
  await channel.send(await coro)
227
228
 
228
229
 
229
- def json_dumps(content) -> bytes:
230
+ def json_dumps(content: Any) -> bytes:
230
231
  """Emulate orjson."""
231
- return dumps( # type: ignore [call-arg]
232
+ return dumps(
232
233
  content,
233
234
  ensure_ascii=False,
234
235
  separators=(",", ":"),
@@ -239,14 +240,18 @@ def json_loads(obj: bytes | str) -> TJSON:
239
240
  """Emulate orjson."""
240
241
  if isinstance(obj, bytes):
241
242
  obj = obj.decode("utf-8")
242
- return loads(obj)
243
+ return cast("TJSON", loads(obj))
243
244
 
244
245
 
245
246
  with suppress(ImportError):
246
247
  from orjson import OPT_NON_STR_KEYS
247
248
  from orjson import dumps as orjson_dumps
248
- from orjson import loads as json_loads # type: ignore[assignment]
249
+ from orjson import loads as orjson_loads
249
250
 
250
- def json_dumps(content) -> bytes:
251
+ def json_dumps(content: Any) -> bytes:
251
252
  """Emulate orjson."""
252
253
  return orjson_dumps(content, default=str, option=OPT_NON_STR_KEYS)
254
+
255
+ def json_loads(obj: bytes | str) -> TJSON:
256
+ """Emulate orjson."""
257
+ return cast("TJSON", orjson_loads(obj))
@@ -5,7 +5,7 @@
5
5
  from __future__ import annotations
6
6
 
7
7
  from functools import partial
8
- from inspect import isclass
8
+ from inspect import isclass, iscoroutinefunction
9
9
  from typing import TYPE_CHECKING, Any, Callable, Self, TypeVar, cast
10
10
 
11
11
  from http_router import PrefixedRoute
@@ -17,11 +17,11 @@ from .errors import (
17
17
  ASGIRequestEntityTooLargeError,
18
18
  )
19
19
  from .logs import logger
20
- from .middleware import LifespanMiddleware, StaticFilesMiddleware, parse_response
20
+ from .middleware import LifespanMiddleware, StaticFilesMiddleware
21
21
  from .request import Request
22
- from .response import Response, ResponseError
22
+ from .response import Response, ResponseError, parse_response
23
23
  from .router import Router
24
- from .utils import close_websocket, iscoroutinefunction, parse_host, to_awaitable
24
+ from .utils import close_websocket, parse_host, to_awaitable
25
25
 
26
26
  if TYPE_CHECKING:
27
27
  import logging
@@ -70,7 +70,7 @@ class App:
70
70
  ... return "Hello, World!"
71
71
  """
72
72
 
73
- exception_handlers: dict[type[BaseException], TExceptionHandler]
73
+ exception_handlers: dict[type, TExceptionHandler]
74
74
 
75
75
  def __init__(
76
76
  self,
@@ -143,13 +143,15 @@ class App:
143
143
 
144
144
  self.exception_handlers[Exception] = handle_unknown_exception
145
145
 
146
- self.internal_middlewares: list = []
146
+ self.internal_middlewares: list[Callable[..., Any]] = []
147
147
 
148
148
  async def __call__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> None:
149
149
  """ASGI entrypoint. Converts the given scope into a request and processes it."""
150
150
  await self.lifespan(scope, receive, send)
151
151
 
152
- async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend): # noqa: PLR0912
152
+ async def __process__( # noqa: PLR0912
153
+ self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend
154
+ ) -> None:
153
155
  """Internal request processing: builds a Request, calls the app, and handles exceptions."""
154
156
  scope["app"] = self
155
157
  scope_type = scope["type"]
@@ -221,7 +223,7 @@ class App:
221
223
  return None
222
224
 
223
225
  def __route__(
224
- self, router: Router, *prefixes: str, hosts: THostsArg | None = None, **_
226
+ self, router: Router, *prefixes: str, hosts: THostsArg | None = None, **_: Any
225
227
  ) -> Self:
226
228
  """Mount this app as a nested application under given prefixes."""
227
229
  if isinstance(hosts, str):
@@ -293,7 +295,7 @@ class App:
293
295
  """
294
296
  return self.router.route(*paths, methods=methods, hosts=hosts, **opts)
295
297
 
296
- def on_startup(self, fn: Callable) -> None:
298
+ def on_startup(self, fn: Callable[[], Any]) -> None:
297
299
  """Register a startup event handler.
298
300
 
299
301
  :param fn: The function to call on startup
@@ -301,7 +303,7 @@ class App:
301
303
  """
302
304
  return self.lifespan.on_startup(fn)
303
305
 
304
- def on_shutdown(self, fn: Callable) -> None:
306
+ def on_shutdown(self, fn: Callable[[], Any]) -> None:
305
307
  """Register a shutdown event handler.
306
308
 
307
309
  :param fn: The function to call on shutdown
@@ -309,7 +311,9 @@ class App:
309
311
  """
310
312
  return self.lifespan.on_shutdown(fn)
311
313
 
312
- def on_error(self, etype: type[BaseException]):
314
+ def on_error(
315
+ self, etype: type[BaseException]
316
+ ) -> Callable[[TVExceptionHandler], TVExceptionHandler]:
313
317
  """Register a custom exception handler for a given exception type.
314
318
 
315
319
  :param etype: The exception type to handle
@@ -335,11 +339,13 @@ class App:
335
339
  class RouteApp(PrefixedRoute):
336
340
  """Custom route to submount an application under a given path prefix."""
337
341
 
338
- def __init__(self, path: str, methods: set, target: App, *, hosts: Iterable[str] | None = None):
342
+ def __init__(
343
+ self, path: str, methods: set[str], target: App, *, hosts: Iterable[str] | None = None
344
+ ) -> None:
339
345
  """Create a submounted app callable for the given prefix."""
340
346
  path = path.rstrip("/")
341
347
 
342
- def app(request: Request):
348
+ def app(request: Request) -> Any:
343
349
  subrequest = request.__copy__(path=request.path[len(path) :])
344
350
  return target.__app__(subrequest, request.receive, request.send)
345
351
 
@@ -6,7 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  from io import BytesIO
8
8
  from tempfile import SpooledTemporaryFile
9
- from typing import TYPE_CHECKING, Callable
9
+ from typing import TYPE_CHECKING, Any, cast
10
10
  from urllib.parse import unquote_to_bytes
11
11
 
12
12
  from multidict import MultiDict
@@ -15,14 +15,14 @@ from .multipart import BaseParser, MultipartParser, QueryStringParser
15
15
  from .utils import parse_options_header
16
16
 
17
17
  if TYPE_CHECKING:
18
- from asgi_tools.request import Request
18
+ from asgi_tools.request import Request, UploadHandler
19
19
 
20
20
 
21
21
  async def read_formdata(
22
22
  request: "Request",
23
23
  max_size: int,
24
- upload_to: Callable | None,
25
- ) -> MultiDict:
24
+ upload_to: "UploadHandler | None",
25
+ ) -> MultiDict[Any]:
26
26
  """Read formdata from the given request."""
27
27
  if request.content_type == "multipart/form-data":
28
28
  reader: FormReader = MultipartReader(request.charset, upload_to, max_size)
@@ -46,9 +46,13 @@ class FormReader:
46
46
  self.charset = charset
47
47
  self.curname = bytearray()
48
48
  self.curvalue = bytearray()
49
- self.form: MultiDict = MultiDict()
49
+ self.form: MultiDict[Any] = MultiDict()
50
50
 
51
- def init_parser(self, _: "Request", max_size: int) -> BaseParser:
51
+ def init_parser(
52
+ self,
53
+ request: "Request", # noqa: ARG002
54
+ max_size: int,
55
+ ) -> BaseParser:
52
56
  return QueryStringParser(
53
57
  {
54
58
  "field_name": self.on_field_name,
@@ -58,13 +62,13 @@ class FormReader:
58
62
  max_size=max_size,
59
63
  )
60
64
 
61
- def on_field_name(self, data: bytes, start: int, end: int):
65
+ def on_field_name(self, data: bytes, start: int, end: int) -> None:
62
66
  self.curname += data[start:end]
63
67
 
64
- def on_field_data(self, data: bytes, start: int, end: int):
68
+ def on_field_data(self, data: bytes, start: int, end: int) -> None:
65
69
  self.curvalue += data[start:end]
66
70
 
67
- def on_field_end(self, *_):
71
+ def on_field_end(self, *_: Any) -> None:
68
72
  self.form.add(
69
73
  unquote_plus(self.curname).decode(self.charset),
70
74
  unquote_plus(self.curvalue).decode(self.charset),
@@ -88,11 +92,11 @@ class MultipartReader(FormReader):
88
92
  "upload_to",
89
93
  )
90
94
 
91
- def __init__(self, charset: str, upload_to: Callable | None, max_size: int):
95
+ def __init__(self, charset: str, upload_to: "UploadHandler | None", max_size: int) -> None:
92
96
  super().__init__(charset)
93
97
  self.name = ""
94
98
  self.headers: dict[bytes, bytes] = {}
95
- self.partdata = BytesIO()
99
+ self.partdata: Any = BytesIO()
96
100
  self.upload_to = upload_to
97
101
  self.max_size = max_size
98
102
 
@@ -114,18 +118,18 @@ class MultipartReader(FormReader):
114
118
  max_size=max_size,
115
119
  )
116
120
 
117
- def on_header_field(self, data: bytes, start: int, end: int):
121
+ def on_header_field(self, data: bytes, start: int, end: int) -> None:
118
122
  self.curname += data[start:end]
119
123
 
120
- def on_header_value(self, data: bytes, start: int, end: int):
124
+ def on_header_value(self, data: bytes, start: int, end: int) -> None:
121
125
  self.curvalue += data[start:end]
122
126
 
123
- def on_header_end(self, *_):
127
+ def on_header_end(self, *_: Any) -> None:
124
128
  self.headers[bytes(self.curname.lower())] = bytes(self.curvalue)
125
129
  self.curname.clear()
126
130
  self.curvalue.clear()
127
131
 
128
- def on_headers_finished(self, *_):
132
+ def on_headers_finished(self, *_args: Any) -> None:
129
133
  _, options = parse_options_header(
130
134
  (self.headers.get(b"content-disposition") or b"").decode(self.charset),
131
135
  )
@@ -135,20 +139,23 @@ class MultipartReader(FormReader):
135
139
 
136
140
  if "filename" in options:
137
141
  upload_to = self.upload_to
142
+ partdata: Any
138
143
  if upload_to is not None:
139
- filename = upload_to(options["filename"])
140
- self.partdata = f = open(filename, "wb+") # noqa: SIM115, PTH123
144
+ partdata = open(upload_to(options["filename"]), "wb+") # noqa: SIM115, PTH123
141
145
 
142
146
  else:
143
- self.partdata = f = SpooledTemporaryFile(self.max_size) # noqa: SIM115
144
- f._file.name = options["filename"] # type: ignore[]
147
+ partdata = SpooledTemporaryFile(self.max_size) # noqa: SIM115
148
+ cast("Any", partdata._file).name = options["filename"]
145
149
 
146
- f.content_type = self.headers.get(b"content-type", b"").decode(self.charset)
150
+ cast("Any", partdata).content_type = self.headers.get(b"content-type", b"").decode(
151
+ self.charset
152
+ )
153
+ self.partdata = partdata
147
154
 
148
- def on_part_data(self, data: bytes, start: int, end: int):
155
+ def on_part_data(self, data: bytes, start: int, end: int) -> None:
149
156
  self.partdata.write(data[start:end])
150
157
 
151
- def on_part_end(self, *_):
158
+ def on_part_end(self, *_: Any) -> None:
152
159
  field_data = self.partdata
153
160
  if isinstance(field_data, BytesIO):
154
161
  self.form.add(self.name, field_data.getvalue().decode(self.charset))
@@ -10,7 +10,7 @@ from contextvars import ContextVar
10
10
  from functools import partial
11
11
  from inspect import isawaitable
12
12
  from pathlib import Path
13
- from typing import TYPE_CHECKING, Awaitable, Callable, Final, Mapping, Self
13
+ from typing import TYPE_CHECKING, Any, Awaitable, Callable, Final, Mapping, Self, cast
14
14
 
15
15
  from http_router import Router
16
16
 
@@ -21,6 +21,8 @@ from .response import Response, ResponseError, ResponseFile, ResponseRedirect, p
21
21
  from .utils import parse_host, to_awaitable
22
22
 
23
23
  if TYPE_CHECKING:
24
+ import logging
25
+
24
26
  from .types import TASGIApp, TASGIMessage, TASGIReceive, TASGIScope, TASGISend
25
27
 
26
28
 
@@ -33,7 +35,7 @@ class BaseMiddleware(metaclass=abc.ABCMeta):
33
35
  """Save ASGI App."""
34
36
  self.bind(app)
35
37
 
36
- def __call__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> Awaitable:
38
+ def __call__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> Awaitable[Any]:
37
39
  """Handle ASGI call."""
38
40
  if scope["type"] in self.scopes:
39
41
  return self.__process__(scope, receive, send)
@@ -41,14 +43,14 @@ class BaseMiddleware(metaclass=abc.ABCMeta):
41
43
  return self.app(scope, receive, send)
42
44
 
43
45
  @abc.abstractmethod
44
- async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend):
46
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> Any:
45
47
  """Do the middleware's logic."""
46
48
  raise NotImplementedError()
47
49
 
48
50
  @classmethod
49
- def setup(cls, **params) -> Callable:
51
+ def setup(cls, **params: Any) -> Callable[..., Any]:
50
52
  """Setup the middleware without an initialization."""
51
- return partial(cls, **params) # type: ignore[abstract]
53
+ return partial(cls, **params)
52
54
 
53
55
  def bind(self, app: TASGIApp | None = None) -> Self:
54
56
  """Rebind the middleware to an ASGI application if it has been inited already."""
@@ -116,17 +118,17 @@ class ResponseMiddleware(BaseMiddleware):
116
118
 
117
119
  """
118
120
 
119
- async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend):
121
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> None:
120
122
  """Parse responses from callbacks."""
121
123
  try:
122
- result = await self.app(scope, receive, self.send)
124
+ result = await self.app(scope, receive, cast("TASGISend", self.send))
123
125
  response = parse_response(result)
124
126
  await response(scope, receive, send)
125
127
 
126
128
  except (ResponseError, ResponseRedirect) as exc:
127
129
  await exc(scope, receive, send)
128
130
 
129
- def send(self, _: TASGIMessage):
131
+ def send(self, _: TASGIMessage) -> None:
130
132
  raise RuntimeError("You can't use send() method in ResponseMiddleware")
131
133
 
132
134
  def bind(self, app: TASGIApp | None = None) -> Self:
@@ -151,7 +153,7 @@ class RequestMiddleware(BaseMiddleware):
151
153
 
152
154
  """
153
155
 
154
- async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend):
156
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> Any:
155
157
  """Replace scope with request object."""
156
158
  return await self.app(Request(scope, receive, send), receive, send)
157
159
 
@@ -201,21 +203,21 @@ class LifespanMiddleware(BaseMiddleware):
201
203
  self,
202
204
  app: TASGIApp | None = None,
203
205
  *,
204
- logger=logger,
206
+ logger: logging.Logger = logger,
205
207
  ignore_errors: bool = False,
206
- on_startup: Callable | list[Callable] | None = None,
207
- on_shutdown: Callable | list[Callable] | None = None,
208
+ on_startup: Callable[[], Any] | list[Callable[[], Any]] | None = None,
209
+ on_shutdown: Callable[[], Any] | list[Callable[[], Any]] | None = None,
208
210
  ) -> None:
209
211
  """Prepare the middleware."""
210
212
  super(LifespanMiddleware, self).__init__(app)
211
213
  self.ignore_errors = ignore_errors
212
214
  self.logger = logger
213
- self.__startup__: list[Callable] = []
214
- self.__shutdown__: list[Callable] = []
215
+ self.__startup__: list[Callable[[], Any]] = []
216
+ self.__shutdown__: list[Callable[[], Any]] = []
215
217
  self.__register__(on_startup, self.__startup__)
216
218
  self.__register__(on_shutdown, self.__shutdown__)
217
219
 
218
- async def __process__(self, _: TASGIScope, receive: TASGIReceive, send: TASGISend):
220
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> None:
219
221
  """Manage lifespan cycle."""
220
222
  while True:
221
223
  message = await receive()
@@ -229,7 +231,9 @@ class LifespanMiddleware(BaseMiddleware):
229
231
  break
230
232
 
231
233
  def __register__(
232
- self, handlers: Callable | list[Callable] | None, container: list[Callable]
234
+ self,
235
+ handlers: Callable[[], Any] | list[Callable[[], Any]] | None,
236
+ container: list[Callable[[], Any]],
233
237
  ) -> None:
234
238
  """Register lifespan handlers."""
235
239
  if not handlers:
@@ -245,11 +249,11 @@ class LifespanMiddleware(BaseMiddleware):
245
249
  await self.run("startup")
246
250
  return self
247
251
 
248
- async def __aexit__(self, *_):
252
+ async def __aexit__(self, *_: object) -> None:
249
253
  """Use the lifespan middleware as a context manager."""
250
254
  await self.run("shutdown")
251
255
 
252
- async def run(self, event: str, _: TASGISend | None = None):
256
+ async def run(self, event: str, _: TASGISend | None = None) -> TASGIMessage:
253
257
  """Run startup/shutdown handlers."""
254
258
  assert event in {"startup", "shutdown"}
255
259
  handlers = getattr(self, f"__{event}__")
@@ -270,11 +274,11 @@ class LifespanMiddleware(BaseMiddleware):
270
274
 
271
275
  return {"type": f"lifespan.{event}.complete"}
272
276
 
273
- def on_startup(self, fn: Callable) -> None:
277
+ def on_startup(self, fn: Callable[[], Any]) -> None:
274
278
  """Add a function to startup."""
275
279
  self.__register__(fn, self.__startup__)
276
280
 
277
- def on_shutdown(self, fn: Callable) -> None:
281
+ def on_shutdown(self, fn: Callable[[], Any]) -> None:
278
282
  """Add a function to shutdown."""
279
283
  self.__register__(fn, self.__shutdown__)
280
284
 
@@ -351,12 +355,14 @@ class RouterMiddleware(BaseMiddleware):
351
355
  self.use_hosts = use_hosts
352
356
  self.router = router or Router(validator=callable)
353
357
 
354
- async def __process__(self, scope: TASGIScope, *args):
358
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> Any:
355
359
  """Get an app and process."""
356
360
  app, scope["path_params"] = self.__dispatch__(scope)
357
- return await app(scope, *args)
361
+ return await app(scope, receive, send)
358
362
 
359
- def __dispatch__(self, scope: TASGIScope) -> tuple[Callable, Mapping | None]:
363
+ def __dispatch__(
364
+ self, scope: TASGIScope
365
+ ) -> tuple[Callable[..., Any], Mapping[str, Any] | None]:
360
366
  """Lookup for a callback."""
361
367
  path = f"{scope.get('root_path', '')}{scope['path']}"
362
368
  host = parse_host(scope["headers"]) if self.use_hosts else None
@@ -367,9 +373,9 @@ class RouterMiddleware(BaseMiddleware):
367
373
  return self.app, {}
368
374
 
369
375
  else:
370
- return match.target, match.params # type: ignore[]
376
+ return cast("Callable[..., Any]", match.target), match.params
371
377
 
372
- def route(self, *args, **kwargs):
378
+ def route(self, *args: Any, **kwargs: Any) -> Any:
373
379
  """Register a route."""
374
380
  return self.router.route(*args, **kwargs)
375
381
 
@@ -436,7 +442,7 @@ class StaticFilesMiddleware(BaseMiddleware):
436
442
  await self.app(scope, receive, send)
437
443
 
438
444
 
439
- BACKGROUND_TASK: Final = ContextVar[list[Awaitable] | None]("background_task", default=None)
445
+ BACKGROUND_TASK: Final = ContextVar[list[Awaitable[Any]] | None]("background_task", default=None)
440
446
 
441
447
 
442
448
  class BackgroundMiddleware(BaseMiddleware):
@@ -462,7 +468,7 @@ class BackgroundMiddleware(BaseMiddleware):
462
468
 
463
469
  """
464
470
 
465
- async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend):
471
+ async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend) -> None:
466
472
  """Run background tasks."""
467
473
  await self.app(scope, receive, send)
468
474
  for task in BACKGROUND_TASK.get() or []:
@@ -471,7 +477,7 @@ class BackgroundMiddleware(BaseMiddleware):
471
477
  BACKGROUND_TASK.set(None) # Clear the context variable
472
478
 
473
479
  @staticmethod
474
- def set_task(task: Awaitable):
480
+ def set_task(task: Awaitable[Any]) -> None:
475
481
  """Set a task for background execution."""
476
482
  tasks = BACKGROUND_TASK.get() or []
477
483
  tasks.append(task)