跳转到主要内容

处理ASGI生命周期的中间件

项目描述

asgi-lifespan-middleware

使用简单的异步上下文管理器接口支持ASGI生命周期的ASGI中间件。

此中间件接受一个要包装的ASGI应用程序和一个异步上下文管理器生命周期。它将运行直接传递给它的生命周期以及ASGI应用程序的生命周期(如果包装的ASGI应用程序支持生命周期)。

示例(Starlette)

Starlette应用程序已经支持生命周期,所以我们只需使用TestClient对无操作的普通ASGI应用程序进行测试。

from contextlib import asynccontextmanager
from typing import AsyncIterator

from starlette.testclient import TestClient
from starlette.types import ASGIApp, Scope, Send, Receive

from asgi_lifespan_middleware import LifespanMiddleware

@asynccontextmanager
async def lifespan(
    # you'll get the wrapped app injected
    app: ASGIApp,
) -> AsyncIterator[None]:
    print("setup")
    yield
    print("teardown")


async def app(scope: Scope, receive: Receive, send: Send) -> None:
    ...  # do nothing


wrapped_app = LifespanMiddleware(
    app,
    lifespan=lifespan,
)

with TestClient(wrapped_app):
    pass

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

asgi_lifespan_middleware-0.1.3.tar.gz (4.7 kB 查看哈希值)

上传时间 源代码

构建分发

asgi_lifespan_middleware-0.1.3-py3-none-any.whl (5.0 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误记录StatusPageStatusPage状态页