1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| from fastapi import FastAPI, Depends, HTTPException from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from pydantic import BaseModel from typing import Optional, List
app = FastAPI()
DATABASE_URL = "sqlite:///./test.db" engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(String)
Base.metadata.create_all(bind=engine)
class UserBase(BaseModel): username: str email: str
class UserCreate(UserBase): password: str
class UserResponse(UserBase): id: int class Config: from_attributes = True
def get_db(): db = SessionLocal() try: yield db finally: db.close()
@app.post("/users", response_model=UserResponse) async def create_user(user: UserCreate, db: Session = Depends(get_db)): db_user = User( username=user.username, email=user.email, hashed_password=user.password ) db.add(db_user) db.commit() db.refresh(db_user) return db_user
@app.get("/users", response_model=List[UserResponse]) async def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = db.query(User).offset(skip).limit(limit).all() return users
@app.get("/users/{user_id}", response_model=UserResponse) async def read_user(user_id: int, db: Session = Depends(get_db)): user = db.query(User).filter(User.id == user_id).first() if not user: raise HTTPException(status_code=404, detail="用户不存在") return user
|