一简介FastAPI https://fastapi.org.cn/ 是一个现代、快速高性能的 Web 框架用于基于标准 Python 类型提示构建 API。教程https://fastapi.org.cn/tutorial/pipinstallfastapi二示例importosimportjsonimportloggingfromtypingimportAnyfrompydanticimportBaseModefromfastapiimportFastAPIfromfastapi.responsesimportFileResponse,JSONResponsefromfastapi.staticfilesimportStaticFiles logging.basicconfig(levellogging.INFo,format%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s)appFastAPI(title标题)app.mount(/static,StaticFiles(directorystatic,namestatic))classApiResponse(BaseModel):code:intmessage:strdata:Any# 全局异常处理器app.exception_handler(Exception)defhandle_exception(request:Request,exe:Exception):logging.error(f异常处理请求路径{request.url}, 捕获到异常{exe})returnJSONResponse(content{code:500,message服务器内部错误请联系管理员,data:None})app.get(/)defroot():logging.info(首页)returnFileResponse(static/index.html)app.get(/api/user)defget_user(request:int)-ApiResponse:user{id:1,username:melong}returnApiResponse(200,ok,user)app.post(/api/user)defadd_user():passapp.delete(/api/user)defdel_user(id:int):passif__name____main__:importuvicorn uvicorn.run(app,host127.0.0.1,port8000)三运行方式一pip installfastapi[standard]fastapi devxxx.py方式二uvicorn xxx:app--reload方式三推荐uvicorn是Python中轻量的web服务器importuvicorn uvicorn.run(app,host127.0.0.1,port8000)