homepage: https://www.starlette.io/
github: https://github.com/encode/starlette
tags:
- ASGI
- python
alias: Starlette
Starlette 是一个轻量的[[ASGI]]框架/工具集,可以利用[[Python]]构建异步网络服务
功能
- 轻量级、低复杂度的HTTP WEB框架;
- 进程内的后台服务;
- 启动以及关闭事件;
- 支持[[Websocket]];
- 基于[[httpx]]的测试客户端;
- [[CORS]]、Gzip、静态文件以及流式响应;
- 会话以及Cookie支持;
- 低依赖
使用
Starlette包括[[应用]]、[[请求]]、[[响应]]、[[路由]]、[[端点]]、[[中间件]]、静态文件挂载以及异常处理等特性。
应用为整个Starlette的处理框架,其实现在 class starlette.applications.Starlette(debug=False, routes=None, middleware=None, exception_handlers=None, on_startup=None, on_shutdown=None, lifespan=None)
中,各个参数的含义如下
- debug - Boolean indicating if debug tracebacks should be returned on errors.(布尔值,表明异常时是否返回调试回调信息。)
- routes - A list of routes to serve incoming HTTP and WebSocket requests.(服务传入 HTTP 和 WebSocket 请求的路由列表。)
- middleware - A list of middleware to run for every request. A starlette application will always automatically include two middleware classes.
ServerErrorMiddleware
is added as the very outermost middleware, to handle any uncaught errors occurring anywhere in the entire stack.ExceptionMiddleware
is added as the very innermost middleware, to deal with handled exception cases occurring in the routing or endpoints.(针对每个请求运行的中间件列表。 starlette 应用程序将始终自动包含两个中间件。 “ServerErrorMiddleware”被添加为最外层的中间件,以处理整个堆栈中任何位置发生的任何未捕获的错误。 “ExceptionMiddleware”被添加为最内部的中间件,以处理路由或端点中发生的已处理异常情况。) - exception_handlers - A mapping of either integer status codes, or exception class types onto callables which handle the exceptions. Exception handler callables should be of the form
handler(request, exc) -> response
and may be either standard functions, or async functions.(状态码或异常类类型到处理异常的可调用对象的映射。 异常处理程序可调用的形式应为handler(request, exc) -> response
,并且可以是标准函数或异步函数。) - on_startup - A list of callables to run on application startup. Startup handler callables do not take any arguments, and may be either standard functions, or async functions.(在应用程序启动时运行的可调用列表。 启动处理程序可调用函数不带任何参数,并且可以是标准函数或异步函数。)
- on_shutdown - A list of callables to run on application shutdown. Shutdown handler callables do not take any arguments, and may be either standard functions, or async functions.(在应用程序关闭时运行的可调用列表。 关闭处理程序可调用函数不带任何参数,并且可以是标准函数或异步函数。)
- lifespan - A lifespan context function, which can be used to perform startup and shutdown tasks. This is a newer style that replaces the
on_startup
andon_shutdown
handlers. Use one or the other, not both.(生命周期上下文函数,可用于执行启动和关闭任务。 这是一种新的方式以替代on_startup
和on_shutdown
处理程序。)
[!warning]
lifespan 和 on_shutdown/on_startup 不能同时使用,只能使用其中一个
[[应用]]包含状态信息,可以通过app.state.*
设置[[应用]]的状态。每一个[[请求]]可以通过request.app
获取请求request
的[[应用]]实例。
架构设计
[!note]
Starlette仅处理不同的事件发生时的响应,最终将响应通过网络层的协议进行传输,其中传输部分使用[[uvicorn]]完成,本质上是将响应的数据传输到一个进程的[[socket]](套接字),并通过[[asyncio]]等异步库开启一个指定协议的网络服务,之后由浏览器渲染到页面上。