使用fastapi 写一个后台管理系统
时间: 2024-04-19 07:08:42 浏览: 394
好的,下面是使用 FastAPI 编写一个后台管理系统的基本步骤:
1. 创建项目
首先,我们需要在终端中创建一个新项目目录,并进入该目录:
```
mkdir fastapi-admin
cd fastapi-admin
```
然后,我们使用 Poetry 创建一个新的 Python 环境,并添加 FastAPI 和相关的依赖项:
```
poetry init -n
poetry add fastapi uvicorn sqlalchemy
```
2. 创建数据库模型
在我们开始编写 API 之前,我们需要定义我们的数据模型。在本例中,我们将创建一个简单的用户模型,包含用户名、电子邮件和密码:
```python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
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)
password = Column(String)
```
3. 创建 API 路由
现在,我们可以创建我们的 API 路由。我们将使用 FastAPI 的路由器和依赖项注入来完成以下操作:
- 创建一个用户
- 获取所有用户
- 获取单个用户
- 更新用户
- 删除用户
```python
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from typing import List
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.get("/users/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
users = crud.get_users(db, skip=skip, limit=limit)
return users
@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
@app.put("/users/{user_id}", response_model=schemas.User)
def update_user(user_id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return crud.update_user(db=db, user=user, db_user=db_user)
@app.delete("/users/{user_id}", response_model=schemas.User)
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return crud.delete_user(db=db, db_user=db_user)
```
4. 创建数据访问层
接下来,我们需要编写我们的数据访问层,这里我们将使用 SQLAlchemy ORM。我们的数据访问层将提供以下功能:
- 创建用户
- 获取所有用户
- 获取单个用户
- 更新用户
- 删除用户
```python
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()
def get_users(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
db_user = models.User(username=user.username, email=user.email, password=user.password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def update_user(db: Session, db_user: models.User, user: schemas.UserUpdate):
db_user.username = user.username
db_user.email = user.email
db_user.password = user.password
db.commit()
db.refresh(db_user)
return db_user
def delete_user(db: Session, db_user: models.User):
db.delete(db_user)
db.commit()
return db_user
```
5. 创建数据模型和输入/输出模式
现在,我们需要创建用于输入和输出的模式。我们将使用 Pydantic 来定义这些模式:
```python
from typing import List
from pydantic import BaseModel
class UserBase(BaseModel):
username: str
email: str
class UserCreate(UserBase):
password: str
class UserUpdate(UserBase):
password: str = None
class Config:
orm_mode = True
class User(UserBase):
id: int
class Config:
orm_mode = True
```
6. 运行应用程序
最后,我们可以使用 Uvicorn 运行应用程序:
```
uvicorn app.main:app --reload
```
现在,我们已经成功地创建了一个使用 FastAPI 的后台管理系统!
阅读全文