一:简介
FastAPI https://fastapi.org.cn/ 是一个现代、快速(高性能)的 Web 框架,用于基于标准 Python 类型提示构建 API。

教程:https://fastapi.org.cn/tutorial/
shell
pip install fastapi
二:示例
python
import os
import json
import logging
from typing import Any
from pydantic import BaseMode
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
logging.basicconfig(
level=logging.INFo,
format="%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s"
)
app = FastAPI(title="标题")
app.mount("/static", StaticFiles(directory="static", name="static"))
class ApiResponse(BaseModel):
code: int
message: str
data: Any
# 全局异常处理器
@app.exception_handler(Exception)
def handle_exception(request: Request, exe: Exception):
logging.error(f"异常处理,请求路径 {request.url}, 捕获到异常 {exe}")
return JSONResponse(content={"code": 500, "message"="服务器内部错误,请联系管理员", data: None})
@app.get("/")
def root():
logging.info("首页")
return FileResponse("static/index.html")
@app.get("/api/user")
def get_user(request: int) -> ApiResponse:
user = {"id": 1, "username": "melong"}
return ApiResponse(200, "ok", user)
@app.post("/api/user")
def add_user():
pass
@app.delete("/api/user")
def del_user(id: int):
pass
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
三:运行
方式一
python
pip install "fastapi[standard]"
fastapi dev "xxx.py"
方式二
python
uvicorn xxx:app --reload
方式三(推荐)
uvicorn是Python中轻量的web服务器
python
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)