Repository navigation
Replies: 2 comments
|
refer: https://asgi.readthedocs.io/en/latest/specs/lifespan.html |
|
For state yielded through ASGI lifespan, you can avoid copying HTTPX's transport implementation: run the lifespan with This minimal example shows startup state reaching an HTTP request: import asyncio
import httpx
from asgi_lifespan import LifespanManager
async def app(scope, receive, send):
if scope["type"] == "lifespan":
while True:
message = await receive()
if message["type"] == "lifespan.startup":
scope["state"]["status"] = "ready"
await send({"type": "lifespan.startup.complete"})
elif message["type"] == "lifespan.shutdown":
await send({"type": "lifespan.shutdown.complete"})
return
elif scope["type"] == "http":
body = scope["state"]["status"].encode()
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": body})
async def main():
async with LifespanManager(app) as manager:
transport = httpx.ASGITransport(app=manager.app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
response = await client.get("/")
assert response.text == "ready"
asyncio.run(main())Install Keep framework-wide References: asgi-lifespan state usage, HTTPX ASGI startup/shutdown. AI-assisted answer using OpenAI Codex. Tested locally with Python 3.11.9, HTTPX 0.28.1, and asgi-lifespan 2.1.0; startup, HTTP state access, and shutdown complete successfully. |
Uh oh!
There was an error while loading. Please reload this page.
recently i am making a TestClient based on httpx.AsyncClient, like what starlette have done
my raw code is
the question is there is no way to set state in
httpx.ASGITransportso i have to re-write a ASGITransport class, but only add a state parameter.
so i was wondering if there's a chance to add state in httpx.ASGITransport
All reactions