python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python FastAPI响应格式

Python中FastAPI responses模块的多种响应格式解析

作者:曲幽

本文将深入解析FastAPI的responses模块,带你掌握多种响应格式的返回方法,并详细讲解模板引擎的使用技巧,静态页面的返回与传参实战,希望对大家有所帮助

还在为FastAPI的响应格式头疼吗?据统计,超过70%的后端开发者在构建Web应用时,曾因响应格式不当导致前端解析错误或用户体验下降。

文章亮点:本文将深入解析FastAPI的responses模块,带你掌握JSON、HTML等多种响应格式的返回方法,并详细讲解模板引擎的使用技巧、静态页面的返回与传参实战,以及参数的高效应用。读完本文,你将能轻松构建功能丰富、交互流畅的Web应用。

FastAPI.responses 响应格式全解析

FastAPI提供了fastapi.responses模块,让你能轻松返回不同格式的响应。默认情况下,FastAPI会自动将返回的字典转换为JSON,但有时你需要更精细的控制。

核心响应类:

示例:显式返回JSON响应。

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/data")
async def get_data():
    return JSONResponse(content={"message": "Hello", "status": "success"}, status_code=200)

通过JSONResponse,你可以自定义状态码和头部信息,比依赖自动转换更灵活。

模板引擎(Jinja2)集成与使用

动态HTML页面离不开模板引擎。FastAPI常用Jinja2来渲染模板,实现数据与视图的分离。

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")  # 模板文件夹

@app.get("/user/{name}", response_class=HTMLResponse)
async def read_user(request: Request, name: str):
    return templates.TemplateResponse("user.html", {"request": request, "username": name})

templates/user.html文件中,你可以使用Jinja2语法:

<!DOCTYPE html>
<html>
<head>
    <title>User Page</title>
</head>
<body>
    <h1>Hello, {{ username }}!</h1>
</body>
</html>

这样,当访问/user/John时,页面会显示"Hello, John!"。模板引擎让动态内容生成变得简单。

HTML静态页面的返回与参数传递

除了动态模板,FastAPI也能直接返回静态HTML文件,并通过参数传递数据。

返回静态HTML文件:使用FileResponse

from fastapi.responses import FileResponse

@app.get("/static-page")
async def get_static_page():
    return FileResponse("static/index.html")  # 假设文件在static文件夹

参数传递到HTML:结合查询参数或路径参数,动态修改页面内容。

from fastapi.responses import HTMLResponse

@app.get("/greet", response_class=HTMLResponse)
async def greet(name: str = "Guest"):
    html_content = f"""
    <html>
        <body>
            <h1>Welcome, {name}!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content)

访问/greet?name=Alice,页面会显示"Welcome, Alice!"。这种方式适合简单页面,无需模板引擎。

路径参数、查询参数等高级用法

参数是Web应用的核心。FastAPI支持多种参数类型,让API更强大。

示例:混合使用路径和查询参数。

from fastapi import FastAPI, Query
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{category}")
async def read_items(
    category: str,
    limit: int = Query(10, gt=0),  # 查询参数,默认10,必须大于0
    skip: int = Query(0, ge=0)     # 默认0,必须大于等于0
):
    # 模拟数据过滤
    data = {"category": category, "limit": limit, "skip": skip}
    return JSONResponse(content=data)

访问/items/books?limit=5&skip=2,返回JSON数据。FastAPI会自动验证参数,无效时会返回错误响应。

完整代码实战参考

下面是一个整合了响应格式、模板引擎和参数使用的完整示例,帮助你快速上手。

from fastapi import FastAPI, Request, Query
from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
import os

app = FastAPI()
templates = Jinja2Templates(directory="templates")

# 返回JSON响应
@app.get("/api/data")
async def get_api_data():
    return JSONResponse(content={"message": "API数据", "code": 200})

# 使用模板引擎渲染HTML
@app.get("/page/{page_name}", response_class=HTMLResponse)
async def render_page(request: Request, page_name: str):
    return templates.TemplateResponse(f"{page_name}.html", {"request": request, "page": page_name})

# 返回静态HTML文件
@app.get("/static")
async def get_static():
    file_path = "static/welcome.html"
    if os.path.exists(file_path):
        return FileResponse(file_path)
    return JSONResponse(content={"error": "文件未找到"}, status_code=404)

# 参数使用示例:查询参数传递到HTML
@app.get("/custom-greet", response_class=HTMLResponse)
async def custom_greet(name: str = Query("旅行者", min_length=1)):
    html = f"""
    <html>
        <head><title>Greeting</title></head>
        <body>
            <h1 style="color: blue;">你好,{name}!欢迎来到FastAPI世界。</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

确保项目结构如下:

- 项目根目录/
  - main.py (以上代码)
  - templates/
    - 例如 index.html, user.html
  - static/
    - welcome.html

运行后,访问不同端点体验功能:/api/data/page/index/static/custom-greet?name=张三

到此这篇关于Python中FastAPI responses模块的多种响应格式解析的文章就介绍到这了,更多相关Python FastAPI响应格式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文