FastAPI是建立在Starlette和Pydantic基础上的,Pydantic是一个基于Python类型提示来定义数据验证、序列化和文档的库。Starlette是一种轻量级的ASGI框架/工具包,是构建高性能Asyncio服务的理性选择
一个简单的基于FastAPI的简单应用可以是
(1)导入 FastAPI。 (2)创建一个 app 实例。 (3)编写一个路径操作装饰器(如 @app.get(“/”))。 (4)编写一个路径操作函数(如 def home(): …) (5)定义返回值 (6)运行开发服务器
Python
from fastapi import FastAPI
app = FastAPI() # 这个实例将是创建你所有 API 的主要交互对象
@app.get("/")
async def root():
return {"message": "Hello world"}Form表单请求
前置库
pip install python-multipart
Python
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/regin")
def regin(username: str = Form(..., max_length=16, min_length=8, regex='[a-zA-Z]'),
password: str = Form(..., max_length=16, min_length=8, regex='[0-9]')):
print(f"username:{username},password:{password}")
return {"username": username}静态文件访问
Python
from fastapi.staticfiles import StaticFiles # 静态文件
app.mount("/static",StaticFiles(directory="statics")) #将/statics文件夹公开到网络/static上Request对象
Python
from fastapi import Request
@app.get("/items")
async def items(request: Request):
return {
"请求URL:": request.url,
"请求ip:": proxyLoc(request.client).host,
"请求宿主:": request.headers.get("user-agent"),
"cookies": request.cookies,
} APIRouter
Python
# main.py
from shop.urls import shop
app = FastAPI()
# 引用route
app.include_router(shop,prefix="/shop",tags=["购物中心接口"])Python
# shop/urls.py
from fastapi import APIRouter
shop = APIRouter()
@shop.get('/food')
async def shop_food():
return {"shop":"food"}

