引入FastAPI

而不是前言

, . , , . . , , . , copy/paste , . , .
 


:

  • ,
  • ,
  • ,

, , HTTP API, POST , , . FastAPI, ?


谁是FastAPI?


FastAPI是一个框架,用于创建简洁,相当快速的HTTP API服务器,具有内置的验证,序列化和异步功能,
正如他们所说的那样。他站在其他两个框架的肩膀上:在FastAPI中与Web一起工作的Starlette,并负责Pydantic的验证


事实证明,该收割机重量轻,不过载且功能强大。


最低要求


FastAPI需要ASGI服务器的工作,默认文档提供uvcorn,基于uvloop,但是FastAPI还可以与其他服务器的工作,例如,C hypercorn


这是我的依赖项:


[packages]
fastapi = "*"
uvicorn = "*"

这绰绰有余。


对于更深入的读者,在文章末尾有一个到bot的存储库的链接,您可以在其中查看用于开发和测试的依赖项。

好,我们pipenv install -d开始了!


构建API


应该注意的是,在FastAPI中设计处理程序的方法与在Flask,Bottle和成千上万的处理程序中非常相似。显然,数百万只苍蝇是不会错的。


首先,我的发布处理路线如下所示:


from fastapi import FastAPI
from starlette import status
from starlette.responses import Response

from models import Body

app = FastAPI()  # noqa: pylint=invalid-name

@app.post("/release/")
async def release(*,
                  body: Body,
                  chat_id: str = None):
    await proceed_release(body, chat_id)
    return Response(status_code=status.HTTP_200_OK)

, , , FastAPI Body, chat_id URL params


models.py:


from datetime import datetime
from enum import Enum

from pydantic import BaseModel, HttpUrl

class Author(BaseModel):
    login: str
    avatar_url: HttpUrl

class Release(BaseModel):
    name: str
    draft: bool = False
    tag_name: str
    html_url: HttpUrl
    author: Author
    created_at: datetime
    published_at: datetime = None
    body: str

class Body(BaseModel):
    action: str
    release: Release

, Pydantic. , , , :


class Body(BaseModel):
    action: str
    releases: List[Release]

FastAPI . . , - — .


Pydantic , HttpUrl, URL , FastAPI . Pydantic


.



FastAPI , , , ,
— !


FastAPI , :


from fastapi import FastAPI, HTTPException, Depends
from starlette import status
from starlette.requests import Request

import settings
from router import api_router
from utils import check_auth

docs_kwargs = {}  # noqa: pylint=invalid-name
if settings.ENVIRONMENT == 'production':
    docs_kwargs = dict(docs_url=None, redoc_url=None)  # noqa: pylint=invalid-name

app = FastAPI(**docs_kwargs)  # noqa: pylint=invalid-name

async def check_auth_middleware(request: Request):
    if settings.ENVIRONMENT in ('production', 'test'):
        body = await request.body()
        if not check_auth(body, request.headers.get('X-Hub-Signature', '')):
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)

app.include_router(api_router, dependencies=[Depends(check_auth_middleware)])

, request.body — , . FastAPI( Starlette) , .


, FastAPI — OpenAPI Swagger/ReDoc , _/docs _/redoc .


. .


, :


from fastapi import APIRouter
from starlette import status
from starlette.responses import Response

from bot import proceed_release
from models import Body, Actions

api_router = APIRouter()  # noqa: pylint=invalid-name

@api_router.post("/release/")
async def release(*,
                  body: Body,
                  chat_id: str = None,
                  release_only: bool = False):

    if (body.release.draft and not release_only) \
            or body.action == Actions.released:
        res = await proceed_release(body, chat_id)
        return Response(status_code=res.status_code)
    return Response(status_code=status.HTTP_200_OK)


, HTTP API- , .



FastAPI — , , , . , (, , 2020- ?
), .


, , , , , FastAPI.



, , . — , , , , .


, , github actions


报告结束了,谢谢大家!


All Articles