FastAPI 和 MongoDB 实现请求头参数处理的示例,并在 React 中进行渲染
# main.py
from fastapi import FastAPI, Request, HTTPException
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel
from bson import ObjectId
from typing import Optional, List
app = FastAPI()
# MongoDB 连接
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client["blogdb"]
collection = db["blogs"]
# 定义博客模型
class Blog(BaseModel):
title: str
content: str
author: str
created_at: str
# 写入100条测试数据
async def create_test_data():
for i in range(100):
blog = Blog(
title=f"测试博客 {i+1}",
content=f"这是第 {i+1} 篇博客的内容",
author=f"作者 {i+1}",
created_at="2025-05-10 12:33:33"
)
await collection.insert_one(blog.dict())
# 初始化时创建测试数据
@app.on_event("startup")
async def startup_event():
await create_test_data()
# 通过请求头参数获取博客
@app.get("/blogs/")
async def get_blogs(request: Request):
# 从请求头中获取参数
api_key = request.headers.get("X-API-Key")
if not api_key or api_key != "your_api_key":
raise HTTPException(status_code=401, detail="Invalid API Key")
blogs = await collection.find().to_list(length=100)
return [{"_id": str(blog["_id"]), **blog} for blog in blogs]