asgi-tools 3.2.0__tar.gz → 3.2.2__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.
- {asgi_tools-3.2.0/asgi_tools.egg-info → asgi_tools-3.2.2}/PKG-INFO +1 -1
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/app.py +29 -10
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/tests.py +2 -3
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/utils.py +12 -1
- {asgi_tools-3.2.0 → asgi_tools-3.2.2/asgi_tools.egg-info}/PKG-INFO +1 -1
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/pyproject.toml +2 -2
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_app.py +93 -1
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_client.py +1 -2
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_compat.py +1 -3
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/LICENSE +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/MANIFEST.in +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/README.md +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/__init__.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/_compat.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/constants.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/errors.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/forms.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/forms.pyx +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/logs.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/middleware.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/multipart.pxd +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/multipart.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/multipart.pyx +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/py.typed +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/request.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/response.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/router.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/types.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools/view.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools.egg-info/SOURCES.txt +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools.egg-info/dependency_links.txt +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools.egg-info/requires.txt +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/asgi_tools.egg-info/top_level.txt +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/setup.cfg +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/setup.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_benchmarks.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_compatibility.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_examples.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_formdata.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_middlewares.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_request.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_responses.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_types.py +0 -0
- {asgi_tools-3.2.0 → asgi_tools-3.2.2}/tests/test_utils.py +0 -0
|
@@ -21,7 +21,7 @@ from .middleware import LifespanMiddleware, StaticFilesMiddleware, parse_respons
|
|
|
21
21
|
from .request import Request
|
|
22
22
|
from .response import Response, ResponseError
|
|
23
23
|
from .router import Router
|
|
24
|
-
from .utils import iscoroutinefunction, parse_host, to_awaitable
|
|
24
|
+
from .utils import close_websocket, iscoroutinefunction, parse_host, to_awaitable
|
|
25
25
|
|
|
26
26
|
if TYPE_CHECKING:
|
|
27
27
|
import logging
|
|
@@ -149,26 +149,35 @@ class App:
|
|
|
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):
|
|
152
|
+
async def __process__(self, scope: TASGIScope, receive: TASGIReceive, send: TASGISend): # noqa: PLR0912
|
|
153
153
|
"""Internal request processing: builds a Request, calls the app, and handles exceptions."""
|
|
154
154
|
scope["app"] = self
|
|
155
|
+
scope_type = scope["type"]
|
|
155
156
|
request = Request(scope, receive, send)
|
|
156
157
|
try:
|
|
157
158
|
response: Response | None = await self.__app__(request, receive, send)
|
|
158
159
|
if response is not None:
|
|
159
|
-
|
|
160
|
+
if scope_type == "websocket":
|
|
161
|
+
await close_websocket(send)
|
|
162
|
+
else:
|
|
163
|
+
await response(scope, receive, send)
|
|
160
164
|
|
|
161
165
|
# Handle exceptions
|
|
162
166
|
except BaseException as exc:
|
|
163
167
|
for etype in type(exc).mro():
|
|
164
168
|
if etype in self.exception_handlers:
|
|
165
|
-
await
|
|
166
|
-
|
|
167
|
-
|
|
169
|
+
response = await self.exception_handlers[etype](request, exc)
|
|
170
|
+
if scope_type == "websocket":
|
|
171
|
+
await close_websocket(send)
|
|
172
|
+
else:
|
|
173
|
+
await parse_response(response)(scope, receive, send)
|
|
168
174
|
break
|
|
169
175
|
else:
|
|
170
176
|
if isinstance(exc, Response):
|
|
171
|
-
|
|
177
|
+
if scope_type == "websocket":
|
|
178
|
+
await close_websocket(send)
|
|
179
|
+
else:
|
|
180
|
+
await exc(scope, receive, send)
|
|
172
181
|
else:
|
|
173
182
|
raise
|
|
174
183
|
|
|
@@ -177,15 +186,22 @@ class App:
|
|
|
177
186
|
) -> Response | None:
|
|
178
187
|
"""Finds and calls a route handler, parses the response, and handles routing exceptions."""
|
|
179
188
|
scope = request.scope
|
|
189
|
+
scope_type = scope["type"]
|
|
180
190
|
path = f"{scope.get('root_path', '')}{scope['path']}"
|
|
181
191
|
host = parse_host(scope["headers"]) if self.use_hosts else None
|
|
182
192
|
try:
|
|
183
193
|
match = self.router(path, scope.get("method", "GET"), host)
|
|
184
194
|
|
|
185
195
|
except ASGINotFoundError as exc:
|
|
196
|
+
if scope_type == "websocket":
|
|
197
|
+
await close_websocket(send)
|
|
198
|
+
return None
|
|
186
199
|
raise ResponseError.NOT_FOUND() from exc
|
|
187
200
|
|
|
188
201
|
except ASGIInvalidMethodError as exc:
|
|
202
|
+
if scope_type == "websocket":
|
|
203
|
+
await close_websocket(send)
|
|
204
|
+
return None
|
|
189
205
|
raise ResponseError.METHOD_NOT_ALLOWED() from exc
|
|
190
206
|
|
|
191
207
|
scope["endpoint"] = match.target
|
|
@@ -193,11 +209,14 @@ class App:
|
|
|
193
209
|
handler = cast("Callable[[Request], Any]", match.target)
|
|
194
210
|
response = await handler(request)
|
|
195
211
|
|
|
196
|
-
if
|
|
212
|
+
if scope_type == "http":
|
|
197
213
|
return parse_response(response)
|
|
198
214
|
|
|
199
|
-
#
|
|
200
|
-
#
|
|
215
|
+
# A websocket handler must manage the connection itself with ResponseWebSocket and
|
|
216
|
+
# return None. Close the connection for an HTTP response instead of dropping it (hang)
|
|
217
|
+
# or sending HTTP messages over the websocket (server crash).
|
|
218
|
+
if response is not None:
|
|
219
|
+
await close_websocket(send)
|
|
201
220
|
|
|
202
221
|
return None
|
|
203
222
|
|
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
|
-
import asyncio
|
|
8
7
|
import binascii
|
|
9
8
|
import io
|
|
10
9
|
import mimetypes
|
|
@@ -395,7 +394,7 @@ async def manage_lifespan(app, timeout: float = 3e-2):
|
|
|
395
394
|
async with aio_spawn(safe_spawn) as task:
|
|
396
395
|
await pipe.send_to_app({"type": "lifespan.startup"})
|
|
397
396
|
|
|
398
|
-
with suppress(TimeoutError
|
|
397
|
+
with suppress(TimeoutError):
|
|
399
398
|
async with aio_timeout(timeout):
|
|
400
399
|
msg = await pipe.receive_from_client()
|
|
401
400
|
if msg["type"] == "lifespan.startup.failed":
|
|
@@ -404,6 +403,6 @@ async def manage_lifespan(app, timeout: float = 3e-2):
|
|
|
404
403
|
yield
|
|
405
404
|
|
|
406
405
|
await pipe.send_to_app({"type": "lifespan.shutdown"})
|
|
407
|
-
with suppress(TimeoutError
|
|
406
|
+
with suppress(TimeoutError):
|
|
408
407
|
async with aio_timeout(timeout):
|
|
409
408
|
await pipe.receive_from_client()
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
7
|
import re
|
|
8
|
+
from contextlib import suppress
|
|
8
9
|
from functools import wraps
|
|
9
10
|
from inspect import isasyncgenfunction, iscoroutinefunction
|
|
10
11
|
from typing import TYPE_CHECKING, Callable, Coroutine, overload
|
|
@@ -15,7 +16,7 @@ from multidict import CIMultiDict
|
|
|
15
16
|
from .constants import BASE_ENCODING
|
|
16
17
|
|
|
17
18
|
if TYPE_CHECKING:
|
|
18
|
-
from .types import TV, TASGIHeaders, TVAsyncCallable
|
|
19
|
+
from .types import TV, TASGIHeaders, TASGISend, TVAsyncCallable
|
|
19
20
|
|
|
20
21
|
|
|
21
22
|
def is_awaitable(fn: Callable) -> bool:
|
|
@@ -125,3 +126,13 @@ def parse_options_header(value: str) -> tuple[str, dict[str, str]]:
|
|
|
125
126
|
rest = rest[match.end() :]
|
|
126
127
|
|
|
127
128
|
return ctype, options
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def close_websocket(send: TASGISend, code: int = 1008) -> None:
|
|
132
|
+
"""Reject/close a websocket without sending HTTP messages.
|
|
133
|
+
|
|
134
|
+
A plain close is used instead of the optional websocket denial-response
|
|
135
|
+
extension, which some servers reject.
|
|
136
|
+
"""
|
|
137
|
+
with suppress(RuntimeError): # the peer may already be gone
|
|
138
|
+
await send({"type": "websocket.close", "code": code})
|
|
@@ -3,7 +3,7 @@ requires = ["setuptools", "wheel", "Cython"]
|
|
|
3
3
|
|
|
4
4
|
[project]
|
|
5
5
|
name = "asgi-tools"
|
|
6
|
-
version = "3.2.
|
|
6
|
+
version = "3.2.2"
|
|
7
7
|
description = "ASGI Toolkit to build web applications"
|
|
8
8
|
readme = "README.md"
|
|
9
9
|
requires-python = ">=3.11,<4"
|
|
@@ -141,7 +141,7 @@ required-imports = ["from __future__ import annotations"]
|
|
|
141
141
|
# min-severity = "warn"
|
|
142
142
|
|
|
143
143
|
[tool.bumpversion]
|
|
144
|
-
current_version = "3.2.
|
|
144
|
+
current_version = "3.2.2"
|
|
145
145
|
commit = false
|
|
146
146
|
tag = false
|
|
147
147
|
message = "build: Bump version: {current_version} → {new_version}"
|
|
@@ -7,7 +7,7 @@ from __future__ import annotations
|
|
|
7
7
|
from pathlib import Path
|
|
8
8
|
from unittest import mock
|
|
9
9
|
|
|
10
|
-
from asgi_tools import HTTPView, ResponseHTML, ResponseWebSocket
|
|
10
|
+
from asgi_tools import HTTPView, ResponseHTML, ResponseText, ResponseWebSocket
|
|
11
11
|
from asgi_tools.app import App, ResponseError
|
|
12
12
|
|
|
13
13
|
|
|
@@ -367,6 +367,98 @@ async def test_websockets(app, client):
|
|
|
367
367
|
assert res.status_code == 200
|
|
368
368
|
|
|
369
369
|
|
|
370
|
+
async def call_websocket(app, path):
|
|
371
|
+
"""Call ``app`` with a websocket scope and collect the ASGI messages it sends."""
|
|
372
|
+
messages = []
|
|
373
|
+
|
|
374
|
+
async def receive():
|
|
375
|
+
return {"type": "websocket.connect"}
|
|
376
|
+
|
|
377
|
+
async def send(message):
|
|
378
|
+
messages.append(message)
|
|
379
|
+
|
|
380
|
+
scope = {
|
|
381
|
+
"type": "websocket",
|
|
382
|
+
"path": path,
|
|
383
|
+
"headers": [],
|
|
384
|
+
"query_string": b"",
|
|
385
|
+
}
|
|
386
|
+
await app(scope, receive, send)
|
|
387
|
+
return messages
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
async def test_websocket_unknown_path_closed():
|
|
391
|
+
app = App()
|
|
392
|
+
|
|
393
|
+
messages = await call_websocket(app, "/unknown")
|
|
394
|
+
types = [msg["type"] for msg in messages]
|
|
395
|
+
|
|
396
|
+
assert types == ["websocket.close"]
|
|
397
|
+
assert not any(msg_type.startswith("http.response") for msg_type in types)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
async def test_websocket_invalid_method_closed():
|
|
401
|
+
app = App()
|
|
402
|
+
|
|
403
|
+
@app.route("/only-post", methods=["POST"])
|
|
404
|
+
async def only_post(request):
|
|
405
|
+
return "POST"
|
|
406
|
+
|
|
407
|
+
messages = await call_websocket(app, "/only-post")
|
|
408
|
+
types = [msg["type"] for msg in messages]
|
|
409
|
+
|
|
410
|
+
assert types == ["websocket.close"]
|
|
411
|
+
assert not any(msg_type.startswith("http.response") for msg_type in types)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
async def test_websocket_handler_error_closed():
|
|
415
|
+
app = App(debug=True)
|
|
416
|
+
|
|
417
|
+
@app.route("/response-error")
|
|
418
|
+
async def response_error(request):
|
|
419
|
+
raise ResponseError.NOT_FOUND()
|
|
420
|
+
|
|
421
|
+
@app.route("/exception")
|
|
422
|
+
async def exception(request):
|
|
423
|
+
raise RuntimeError("boom")
|
|
424
|
+
|
|
425
|
+
@app.on_error(Exception)
|
|
426
|
+
async def handle_exception(request, exc):
|
|
427
|
+
return ResponseText("handled")
|
|
428
|
+
|
|
429
|
+
for path in ("/response-error", "/exception"):
|
|
430
|
+
messages = await call_websocket(app, path)
|
|
431
|
+
types = [msg["type"] for msg in messages]
|
|
432
|
+
assert types == ["websocket.close"]
|
|
433
|
+
assert not any(msg_type.startswith("http.response") for msg_type in types)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
async def test_websocket_http_response_not_sent():
|
|
437
|
+
app = App()
|
|
438
|
+
|
|
439
|
+
@app.route("/plain")
|
|
440
|
+
async def plain(request):
|
|
441
|
+
return ResponseText("ok")
|
|
442
|
+
|
|
443
|
+
messages = await call_websocket(app, "/plain")
|
|
444
|
+
types = [msg["type"] for msg in messages]
|
|
445
|
+
|
|
446
|
+
assert types == ["websocket.close"]
|
|
447
|
+
assert not any(msg_type.startswith("http.response") for msg_type in types)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
async def test_http_not_found_unchanged(client_cls):
|
|
451
|
+
app = App()
|
|
452
|
+
client = client_cls(app)
|
|
453
|
+
|
|
454
|
+
res = await client.get("/unknown")
|
|
455
|
+
body = await res.body()
|
|
456
|
+
|
|
457
|
+
assert res.status_code == 404
|
|
458
|
+
assert body == b"Nothing matches the given URI"
|
|
459
|
+
assert res.headers["content-length"] == str(len(body))
|
|
460
|
+
|
|
461
|
+
|
|
370
462
|
async def test_app_lifespan(app, client):
|
|
371
463
|
side_effects = {}
|
|
372
464
|
|
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
from __future__ import annotations
|
|
6
6
|
|
|
7
|
-
import asyncio
|
|
8
7
|
import io
|
|
9
8
|
from pathlib import Path
|
|
10
9
|
|
|
@@ -277,7 +276,7 @@ async def test_timeouts(app, client):
|
|
|
277
276
|
assert res.status_code == 200
|
|
278
277
|
assert await res.text() == "OK"
|
|
279
278
|
|
|
280
|
-
with pytest.raises(
|
|
279
|
+
with pytest.raises(TimeoutError):
|
|
281
280
|
await client.get("/sleep/10", timeout=0.1)
|
|
282
281
|
|
|
283
282
|
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import asyncio
|
|
6
5
|
from multiprocessing import Value
|
|
7
6
|
|
|
8
7
|
import pytest
|
|
@@ -27,7 +26,7 @@ async def test_aio_timeout_disabled():
|
|
|
27
26
|
|
|
28
27
|
|
|
29
28
|
async def test_aio_timeout():
|
|
30
|
-
with pytest.raises(
|
|
29
|
+
with pytest.raises(TimeoutError):
|
|
31
30
|
async with aio_timeout(1e-2):
|
|
32
31
|
await aio_sleep(1)
|
|
33
32
|
|
|
@@ -50,7 +49,6 @@ async def test_aio_wait_first_completed():
|
|
|
50
49
|
|
|
51
50
|
|
|
52
51
|
def test_compat_json():
|
|
53
|
-
|
|
54
52
|
data = json_dumps({"test": 42})
|
|
55
53
|
assert data
|
|
56
54
|
assert isinstance(data, bytes)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|