from fastapi import FastAPI, Form, File, UploadFile from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional
# 创建FastAPI应用实例 app = FastAPI(title="简单的FastAPI应用", version="1.0.0")
# 添加CORS中间件 app.add_middleware( CORSMiddleware, allow_origins=["*"], # 允许所有来源,生产环境中应该设置具体域名 allow_credentials=True, allow_methods=["*"], # 允许所有HTTP方法 allow_headers=["*"], # 允许所有请求头 )
# 定义JSON数据模型 class UserProfile(BaseModel): username: str email: str age: int bio: Optional[str] = None
class Product(BaseModel): name: str price: float category: str description: Optional[str] = None
# 根路径 @app.get("/") async def read_root(): return {"message": "欢迎使用FastAPI!", "status": "运行中"}
# 接收JSON数据的接口 @app.post("/api/user") async def create_user(user: UserProfile): """ 接收JSON格式的用户数据 """ return { "message": "用户创建成功", "user_data": user, "status": "success" }
@app.post("/api/product") async def create_product(product: Product): """ 接收JSON格式的产品数据 """ return { "message": "产品创建成功", "product_data": product, "product_id": 12345, "status": "success" }
# 接收form-data的接口 @app.post("/api/form/user") async def create_user_form( username: str = Form(...), email: str = Form(...), age: int = Form(...), bio: Optional[str] = Form(None) ): """ 接收form-data格式的用户数据 """ return { "message": "用户表单提交成功", "form_data": { "username": username, "email": email, "age": age, "bio": bio }, "status": "success" }
@app.post("/api/form/upload") async def upload_file( title: str = Form(...), description: Optional[str] = Form(None), file: UploadFile = File(...) ): """ 接收form-data格式数据,包含文件上传 """ return { "message": "文件上传成功", "form_data": { "title": title, "description": description, "filename": file.filename, "content_type": file.content_type, "file_size": len(await file.read()) if file else 0 }, "status": "success" }
@app.post("/api/form/mixed") async def mixed_form_data( name: str = Form(...), price: float = Form(...), category: str = Form(...), description: Optional[str] = Form(None), image: Optional[UploadFile] = File(None) ): """ 混合form-data:包含普通字段和可选文件 """ file_info = None if image: content = await image.read() file_info = { "filename": image.filename, "content_type": image.content_type, "size": len(content) } return { "message": "混合数据提交成功", "product_info": { "name": name, "price": price, "category": category, "description": description }, "file_info": file_info, "status": "success" }
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
|