Uvicorn:
- 框架
- 不同协议对应不同的
protocol类,使用loop.create_server创建server. - 使用
Middleware包装用户的async function. 可以预先获取scope, send ,receive. 根据scope的内容进行相应的处理,再调用async function. - multiple workers 是通过 socket share实现的,在主进程先创建socket,
bind,set_inheratible(True), 之后传入到子进程中供loop.create_server使用.
- 不同协议对应不同的
- protocol
- lifespan
注意,uvicorn 还使用了CO_REUSEADDR
Starlette
class Starlette
操作都代理到Router class和Middleware中
- routes和lifespan都是
Router对象进行管理 - middleware 是一层包一层的,最内层为
Router对象, 而一个Router对象又包括多个Route对象 Route/WebSocketRoute/Mount/Host/Lifespan包含matchs(scope)和__call__(scope, receive, send)函数- Middleware 包含
__call__(scope, receive, send)函数
整个程序的运行流程为:
- asgi 接到请求到调用最外层的callable ASGI 对象(支持call(scope, receive, send)).
- 在每一层middleware 中进行一些数据的处理,之后再await下一层的call
- 直到最后一层的Route对象,Route对象会调用各个route的match检查是否match, 再await match的Route对象
- 总之,整个程序就是一层一层的ASGI callable对象进行串联起来的. 中间传递的数据是(scope, receive, send)
class Route
- 将传入的对象(装饰器包装的那些route函数) 包装为Asgi app. i.e. 一个callable 对象, 接受(scope, recevie, send).
def request_response(func: typing.Callable) -> ASGIApp:is_coroutine = asyncio.iscoroutinefunction(func)async def app(scope: Scope, receive: Receive, send: Send) -> None:request = Request(scope, receive=receive, send=send)if is_coroutine:response = await func(request)else:response = await run_in_threadpool(func, request)await response(scope, receive, send)return app
- Tricks:
- 同时提供
add_xxx和xxx装饰器函数,在装饰器版本中直接调用add_xxx来代理相应功能 - 虽然api是使用的decorator的形式,当是内部各个类的实现是普通形式
- 同时提供
- Other modules
