Trigger http.lifecycle.request signal in ASGI mode (#2451)

Co-authored-by: Adam Hopkins <adam@amhopkins.com>
This commit is contained in:
Vetési Zoltán 2022-06-16 10:55:50 +02:00 committed by GitHub
parent 65b53a5f3f
commit b87982769f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 0 deletions

View File

@ -163,6 +163,13 @@ class ASGIApp:
instance.request_body = True instance.request_body = True
instance.request.conn_info = ConnInfo(instance.transport) instance.request.conn_info = ConnInfo(instance.transport)
await sanic_app.dispatch(
"http.lifecycle.request",
inline=True,
context={"request": instance.request},
fail_not_found=False,
)
return instance return instance
async def read(self) -> Optional[bytes]: async def read(self) -> Optional[bytes]:

View File

@ -13,6 +13,7 @@ from sanic.exceptions import BadRequest, Forbidden, ServiceUnavailable
from sanic.request import Request from sanic.request import Request
from sanic.response import json, text from sanic.response import json, text
from sanic.server.websockets.connection import WebSocketConnection from sanic.server.websockets.connection import WebSocketConnection
from sanic.signals import RESERVED_NAMESPACES
@pytest.fixture @pytest.fixture
@ -513,3 +514,34 @@ async def test_request_exception_suppressed_by_middleware(app):
_, response = await app.asgi_client.get("/error-prone") _, response = await app.asgi_client.get("/error-prone")
assert response.status_code == 403 assert response.status_code == 403
@pytest.mark.asyncio
async def test_signals_triggered(app):
@app.get("/test_signals_triggered")
async def _request(request):
return text("test_signals_triggered")
signals_triggered = []
signals_expected = [
# "http.lifecycle.begin",
# "http.lifecycle.read_head",
"http.lifecycle.request",
"http.lifecycle.handle",
"http.routing.before",
"http.routing.after",
"http.lifecycle.response",
# "http.lifecycle.send",
# "http.lifecycle.complete",
]
def signal_handler(signal):
return lambda *a, **kw: signals_triggered.append(signal)
for signal in RESERVED_NAMESPACES["http"]:
app.signal(signal)(signal_handler(signal))
_, response = await app.asgi_client.get("/test_signals_triggered")
assert response.status_code == 200
assert response.text == "test_signals_triggered"
assert signals_triggered == signals_expected