深色浅色模式切换
fastapi安装
更新时间: 2025/6/21 本章字数: 0 字 预计阅读时长: 0 分钟
本章总结
安装
sh
pip install fastapi
sh
pip install uvicorn
首页
python
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
try:
uvicorn.run(app, host="127.0.0.1", port=9987)
except KeyboardInterrupt:
print("Server stop")
返回html
python
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import uvicorn
app = FastAPI()
# 需要在主目录下新建一个templates文件夹专门存放html文件
templates = Jinja2Templates(directory="templates")
# 新建一个static文件存放静态资源
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
if __name__ == "__main__":
try:
uvicorn.run(app, host="127.0.0.1", port=9987)
except KeyboardInterrupt:
print("Server stop")
自定义404页面
python
@app.exception_handler(HTTP_404_NOT_FOUND)
async def custom_404_handler(request, exc):
return JSONResponse(
status_code=HTTP_404_NOT_FOUND,
content={"code": 404, "message": "The page you are visiting does not exist!"}
)
自定义405页面
python
@app.exception_handler(HTTP_405_METHOD_NOT_ALLOWED)
async def custom_405_handler(request, exc):
return JSONResponse(
status_code=HTTP_405_METHOD_NOT_ALLOWED,
content={"code": 405, "message": "The request method is not allowed!"}
)
完整
python
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from starlette.status import HTTP_404_NOT_FOUND, HTTP_405_METHOD_NOT_ALLOWED
import uvicorn
app = FastAPI()
@app.exception_handler(HTTP_404_NOT_FOUND)
async def custom_404_handler(request, exc):
return JSONResponse(
status_code=HTTP_404_NOT_FOUND,
content={"code": 404, "message": "The page you are visiting does not exist!"}
)
@app.exception_handler(HTTP_405_METHOD_NOT_ALLOWED)
async def custom_405_handler(request, exc):
return JSONResponse(
status_code=HTTP_405_METHOD_NOT_ALLOWED,
content={"code": 405, "message": "The request method is not allowed!"}
)
if __name__ == "__main__":
try:
uvicorn.run(app, host="127.0.0.1", port=9987)
except KeyboardInterrupt:
print("Server stop")