通过创建pydantic模型进行验证提交数据
我们去通过传入数据库连接以及参数等进行数据库操作,包括创建用户、查询用户等,返回的是orm模型对象。
接下来,我们就是在实际的接口中调用
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import Column, Integer, String, Boolean
mysql_url = "mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8".format(
username="root", password="xxxxx;;", host="xxxxx", port=3306, database="sqlalchemy_db")
# SQLALCHEMY_DATABASE_URL = "sqlite:///.test.db"
engine = create_engine(
mysql_url,
# SQLALCHEMY_DATABASE_URL,
# connect_args 参数只有sqlite才有
# connect_args = {
# "check_same_thread": False
# }
)
# 该类的每个实例都是一个数据库会话,该类本身还不是数据库会话,但是一旦我们创建了SessionLocal的实例,这个实例将是实际的数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 创建数据库基类
Base = declarative_base()
# 创建两个数据库模型,继承自Base基类
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String(20), unique=True, index=True)
hashed_password = Column(String(20))
is_active = Column(Boolean, default=True)
items = relationship("Item", back_populates="owner")
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(10), index=True)
description = Column(String(10), index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="items")
# 那么我们如何将该模型对应到数据库表呢? 很简单
# Base.metadata.create_all(bind=engine)
#___________________________________________
from pydantic import BaseModel
from sqlalchemy.orm import Session
class UserBase(BaseModel):
email: str
class UserCreate(UserBase):
"""请求验证模型"""
password: str
class Users(UserBase):
"""响应模型"""
id: int
is_active: bool
class Config:
orm_mode = True
def get_user(db: Session, user_id: int):
"""通过id查询用户"""
return db.query(User).filter(User.id == user_id).first()
def db_create_user(db: Session, user: UserCreate):
"""创建用户"""
fake_hashed_password = user.password + "falsehash"
print(">>>>>", user, fake_hashed_password)
db_user = User(email=user.email, hashed_password=fake_hashed_password)
db.add(db_user)
db.commit() # 提交保存到数据库中
db.refresh(db_user)
return db_user
# 创建一个依赖
def get_db():
"""每一个请求处理完毕后会关闭当前连接,不同的请求使用不同的连接"""
db = SessionLocal()
try:
yield db
finally:
db.close()
from fastapi import FastAPI, Depends, HTTPException
app = FastAPI()
@app.post("/users", response_model=Users)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
"""创建用户接口"""
return db_create_user(db=db, user=user)
@app.get("/users/{user_id}", response_model=Users)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = get_user(db=db, user_id=user_id)
if not db_user:
raise HTTPException(status_code=404, detail="user not exists")
return db_user
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app", debug=True)
我们去用postman去请求下创建下用户
查询下账户
我们去查询不存在的id