首页 > 数据库 >FastAPI系列:fastapi定制的数据库操作库sqlmodel

FastAPI系列:fastapi定制的数据库操作库sqlmodel

时间:2024-02-28 18:46:58浏览次数:33  
标签:engine Users FastAPI db session user fastapi import sqlmodel

官网

sqlmodel

安装

# 安装sqlmodel会自动安装pydantic和sqlalchemy
pip install sqlmodel

使用

# 步骤1,创建sqlmodel引擎
from sqlmodel import create_engine

# driver://用户名:密码@ip/数据库
engine = create_engine("mysql+mysqldb://root:123456@localhost/api")

# 步骤2,定义数据库表映射模型
from typing import Optional
from sqlmodel import Field, SQLModel

class Users(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    nikename: str
    password: str
    email: str

# 步骤3,通过sqlmodel创建逻辑业务表
SQLModel.metadata.create_all(engine)

快速入门之增删改查

from user import Users, engine
from sqlmodel import Field, Session, SQLModel


if __name__  ==  '__main__':
    # 增
    user1 = Users(name='jack', nikename='jj', password='123456', email='[email protected]')
    user2 = Users(name='yamu', nikename='yy', password='123456', email='[email protected]')

    with Session(engine) as session:
        session.add(user1)
        session.add(user2)
        session.commit()
        
    # 查,通过select()
    ## 查询全部数据
    with Session(engine) as session:
        allusers = select(Users)
        results = session.exec(allusers)
        for user in results:
            print(user)
            
    ## 根据条件查询单个数据
    with Session(engine) as session:
        userresult = select(Users).where(Users.name == 'jack')
        # 获取第一条记录
        user = session.exec(userresult).first()
        print(user)
        
    ## 多条件查询
    with Session(engine) as session:
        userresult = select(Users).where(Users.name == 'jack').where(Users.nikename == 'jj')
        # 获取全部记录
        users = session.exec(userresult).all()
        print(users)
        
    ## 另一种多条件查询
    with Session(engine) as session:
        userresult = select(Users).where(Users.name == 'jack', Users.nikename == 'jj')
        # 获取全部记录
        users = session.exec(userresult).all()
        print(users)
        
        
   	# 更新
    with Session(engine) as session:
        # 先查询符合条件的记录
        results = session.exec(select(Users).where(Users.name=='jack'))
        user = results.first()
        user.email  = '[email protected]'
        session.add(user)
        session.commit()
        session.refresh(user)
        
   	## 批量更新  
	with Session(engine) as session:
        # 通过update
        updateusers = update(Users).where(Users.name == 'jack')
        results = session.exec(updateusers.values(email='[email protected]'))
        session.commit()
        
    # 删除
    with Session(engine) as session:
        # 查询符合条件的记录
        user = session.exec(select(Users).where(Users.name == 'jack')).first()
        # 删除该记录
        session.delete(user)
        session.commit()
        
    with Session(engine) as session:
        # 通过delete模块筛选 所有 符合条件的记录,批量进行删除操作
        user = session.exec(delete(Users).where(Users.name == 'jack'))
        session.commit()

异步sqlmodel操作

安装依赖aiomysql

pip install aiomysql

使用

# db/database.py
#  导入异步引擎的模块
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker

# 创建异步引擎对象
async_engine = create_async_engine('mysql+aiomysql://root:[email protected]/api', echo=True)

# 创建orm模型基类
Base = declarative_base()

# 创建异步会话管理对象
sessionLocal = sessionmaker(bind=async_engine, expire_on_commit=False, class_=AsyncSession)

# dependencies/session.py
from sqlalchemy.ext.asyncio import AsyncSession
from typing import AsyncGenerator
from db.database import sessionLocal

async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
    db_session = None
    try:
        db_session = sessionLocal()
        yield db_session
    finally:
        await db_session.close()

# services/user.py
from sqlalchemy import select, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from models.model import User
from db.database import async_engine, Base
class UserServices:
    @staticmethod
    async def get_user(async_session: AsyncSession, user_id: int):
        result = await async_session.execute(select(User).where(User.id == user_id))
        return result.scalars().first()

# api/user.py
router_user = APIRouter(prefix='/user', tags=['用户'])
@router_user.get('/{user_id}')
async def get(user_id: int, db_session: AsyncSession=Depends(get_db_session)): # 通过依赖注入的方式获取session会话
  result  = await UserServices.get_user(db_session, user_id) # 将session会话对象传递到services方法中
  return {
        'code': 200,
        'msg': 'success',
        'data': {
            'result': result
        }
    }

标签:engine,Users,FastAPI,db,session,user,fastapi,import,sqlmodel
From: https://www.cnblogs.com/weiweivip666/p/18041425

相关文章

  • FastAPI系列:自定义认证
    fromtypingimportOptional,TuplefromfastapiimportFastAPI,RequestfrompydanticimportBaseModel#通过starlette.authentication导入AuthenticationBackendfromstarlette.authenticationimportAuthenticationBackend,AuthenticationError,AuthCredentials,S......
  • FastAPI系列:依赖注入
    函数式依赖项fromfastapiimportFastAPIfromfastapiimportQuery,Dependsfromfastapi.exceptionsimportHTTPExceptionapp=FastAPI()defusername_check(username:str=Query(...)):ifusername!='zhong':raiseHTTPException(status_code......
  • FastAPI系列:环境配置读取
    依赖包pipinstallpython-dotenv使用#.env文件ADMIN_EMAIL="[email protected]"APP_NAME="ChimichangApp"#config.pyfrompydantic_settingsimportBaseSettingsclassSettings(BaseSettings):app_name:str="AwesomeAPI"......
  • FastAPI系列:后台任务进程
    注:后台任务应附加到响应中,并且仅在发送响应后运行用于将单个后台任务添加到响应中fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponsefromstarlette.backgroundimportBackgroundTaskfrompydanticimportBaseModelapp=FastAPI()classUser(B......
  • FastAPI系列:中间件
    中间件介绍中间件是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应返回之前工作装饰器版中间件1.必须使用装饰器@app.middleware("http"),且middleware_type必须为http2.中间件参数:request,call_next,且call_next它将接收request作为参数@app.middleware("h......
  • FastAPI系列:模型用法
    模型基本用法frompydanticimportBaseModelclassItem(BaseModel):#通过继承BaseModelname:strprice:floatis_offer:Union[bool,None]=None常用的模型属性和方法dict()#将数据模型的字段和值封装成字典json()#将数据模型的字段和值封装成json格......
  • FastAPI系列:上传文件File和UploadFile
    上传文件#file仅适用于小文件@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"Nofilesent"}else:return{"file_size":len(file)}......
  • FastAPI系列:路径参数额外校验Path
    路径参数额外校验PathfromfastapiimportPathapp=FastAPI()@app.get('/items/{item_id}')asyncdefread_items(item_id:str=Path(default=None,max_length=3,min_length=1,title='theidofitemtoget')):"""def......
  • FastAPI系列:查询字符串参数
    单个查询字符串@app.get('/index/{username}')defindex(username:str,id:int):#id为查询字符串?id=5return{"message":"success","username":username,"id":id}可选的查询字符串参数@app.get('/items/{item_id}......
  • FastAPI系列:APIRouter实例的路由注册
    APIRouter实例的路由注册API端点路由注册大致分为3种:1.基于app实例对象提供的装饰器或函数进行注册2.基于FastAPI提供的APIRouter类的实例对象提供的装饰器或函数进行注册3.通过直接实例化APIRoute对象且添加的方式进行注册路由注册方式基于APIRouter的实例对象实现路由注册......