Lifespan
Mangum supports the ASGI Lifespan protocol. This allows applications to define lifespan startup and shutdown event handlers.
from mangum import Mangum
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup_event():
pass
@app.on_event("shutdown")
async def shutdown_event():
pass
@app.get("/")
def read_root():
return {"Hello": "World"}
handler = Mangum(app, lifespan="auto")
Configuring Lifespan events
Lifespan support is automatically determined unless explicitly turned on or off. A string value option is used to configure lifespan support, the choices are auto
, on
, and off
.
Options
-
auto
Application support for lifespan is inferred using the state transitions. Any error that occurs during startup will be logged and the ASGI application cycle will continue unless a
lifespan.startup.failed
event is sent. -
on
Application support for lifespan is explicit. Any error that occurs during startup will be raised and a 500 response will be returned.
-
off
Application support for lifespan is ignored. The application will not enter the lifespan cycle context.
Defaults to auto
.
State machine
The LifespanCycle
is a state machine that handles ASGI lifespan
events intended to run before and after HTTP requests are handled.
LifespanCycle
mangum.protocols.lifespan.LifespanCycle
(app, lifespan)Manages the application cycle for an ASGI lifespan
connection.
- app - An asynchronous callable that conforms to version 3.0 of the ASGI specification. This will usually be an ASGI framework application instance.
- lifespan - A string to configure lifespan support. Choices are
auto
,on
, andoff
. Default isauto
. - state - An enumerated
LifespanCycleState
type that indicates the state of the ASGI connection. - exception - An exception raised while handling the ASGI event. This may or may not be raised depending on the state.
- app_queue - An asyncio queue (FIFO) containing messages to be received by the application.
- startup_event - An asyncio event object used to control the application startup flow.
- shutdown_event - An asyncio event object used to control the application shutdown flow.
run
(self)Calls the application with the lifespan
connection scope.
receive
(self)Awaited by the application to receive ASGI lifespan
events.
send
(self, message)Awaited by the application to send ASGI lifespan
events.
startup
(self)Pushes the lifespan
startup event to the queue and handles errors.
shutdown
(self)Pushes the lifespan
shutdown event to the queue and handles errors.
Context manager
Unlike the HTTPCycle
class, the LifespanCycle
is also used as a context manager in the adapter class. If lifespan support is turned off, then the application never enters the lifespan cycle context.
with ExitStack() as stack:
# Ignore lifespan events entirely if the `lifespan` setting is `off`.
if self.lifespan in ("auto", "on"):
asgi_cycle: typing.ContextManager = LifespanCycle(
self.app, self.lifespan
)
stack.enter_context(asgi_cycle)
The magic methods __enter__
and __exit__
handle running the async tasks that perform startup and shutdown functions.
def __enter__(self) -> None:
"""
Runs the event loop for application startup.
"""
self.loop.create_task(self.run())
self.loop.run_until_complete(self.startup())
def __exit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]],
exc_value: typing.Optional[BaseException],
traceback: typing.Optional[types.TracebackType],
) -> None:
"""
Runs the event loop for application shutdown.
"""
self.loop.run_until_complete(self.shutdown())
LifespanCycleState
mangum.protocols.lifespan.LifespanCycleState
(*values)The state of the ASGI lifespan
connection.
- CONNECTING - Initial state. The ASGI application instance will be run with
the connection scope containing the
lifespan
type. - STARTUP - The lifespan startup event has been pushed to the queue to be received by the application.
- SHUTDOWN - The lifespan shutdown event has been pushed to the queue to be received by the application.
- FAILED - A lifespan failure has been detected, and the connection will be closed with an error.
- UNSUPPORTED - An application attempted to send a message before receiving the lifespan startup event. If the lifespan argument is "on", then the connection will be closed with an error.