FastAPI

https://github.com/tiangolo/fastapi

写 web 就它了,学习中……

参考作者的文章:https://fastapi.tiangolo.com/alternatives/ ,了解这个框架的来由。

Types

https://fastapi.tiangolo.com/python-types/

例子

来一个长轮询的消息服务,比 tornado 版的更短些:

#!/usr/bin/env python3

import asyncio
import collections
from typing import Dict, List

from fastapi import FastAPI, HTTPException

todos: Dict[str, List[asyncio.Future]] = collections.defaultdict(list)
app = FastAPI()


@app.get("/{token:path}")
async def get(token: str):
    future = asyncio.Future()
    todos[token].append(future)
    return await future


@app.post("/{token:path}")
async def post(token: str, payload: dict = {}):
    try:
        future = todos[token].pop()
    except IndexError:
        raise HTTPException(status_code=404)
    future.set_result(payload)

限于框架和篇幅,用起来时,仅支持 JSON 消息。另外,python annotation 还是很好用的。

但是有个问题,GET 中途断开的情况,不好处理。参考这个版本: https://gist.github.com/lwzm/c691285214b4be0e7c382ebfd384818a