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).
  1. def request_response(func: typing.Callable) -> ASGIApp:
  2. is_coroutine = asyncio.iscoroutinefunction(func)
  3. async def app(scope: Scope, receive: Receive, send: Send) -> None:
  4. request = Request(scope, receive=receive, send=send)
  5. if is_coroutine:
  6. response = await func(request)
  7. else:
  8. response = await run_in_threadpool(func, request)
  9. await response(scope, receive, send)
  10. return app
  • Tricks:
    • 同时提供add_xxx和xxx装饰器函数,在装饰器版本中直接调用add_xxx来代理相应功能
    • 虽然api是使用的decorator的形式,当是内部各个类的实现是普通形式
  • Other modules

databases

aiosqlite