Documentation IndexFetch the complete documentation index at: /llms.txtUse this file to discover all available pages before exploring further.
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
你正在查看中文版本。切换到英文 →
FastAPI 基于 Python 类型提示构建的高性能 Web 框架学习笔记,系统涵盖路由定义与路径参数绑定、Pydantic 请求体验证、依赖注入系统、CORS 跨域中间件配置、SQLAlchemy 数据库集成、OAuth2 认证授权以及文件上传与后台任务等核心功能用法详解。
pip install fastapi pip install "uvicorn[standard]"
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
uvicorn main:app --reload
from typing import Optional @app.get("/users/{user_id}") async def read_user( user_id: int, skip: int = 0, limit: int = 10, q: Optional[str] = None ): return {"user_id": user_id, "skip": skip, "limit": limit, "q": q}
from pydantic import BaseModel class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None @app.post("/items/") async def create_item(item: Item): return item
class UserOut(BaseModel): username: str email: str @app.post("/users/", response_model=UserOut) async def create_user(user: User): return user # 自动过滤敏感字段
from fastapi import Depends def get_db(): db = Database() try: yield db finally: db.close() @app.get("/users/") async def read_users(db = Depends(get_db)): return db.query_users()
from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(bind=engine) def get_db(): db = SessionLocal() try: yield db finally: db.close()
from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): return {"token": token}
from fastapi import File, UploadFile @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename}
from fastapi import BackgroundTasks def send_email(email: str): # 发送邮件逻辑 pass @app.post("/send-notification/") async def send_notification( email: str, background_tasks: BackgroundTasks ): background_tasks.add_task(send_email, email) return {"message": "Email will be sent"}
此页面对您有帮助吗?