fastapi篇(七)
SQLAlchemy
orm框架,操作数据库的框架,把数据库实体高度封装成了python对象;有了它,也就意味着我们可以在不熟悉sql语句的同时,对数据库执行操作
在视图函数中,主要涉及和数据库的交互,最基本的就是crud
1、创建数据库引擎函数
from sqlalchemy import create_engine
mysql_engine = create_engine(f"mysql+pymysql://root:root123456@172.23.60.12:5688/accounting_company", encoding='utf-8')
2、创建本地会话
from sqlalchemy.orm import sessionmaker, declarative_base
def db_session(database='sqlite'):
if database == 'mysql':
return sessionmaker(bind=mysql_engine(), expire_on_commit=False)()
if not getattr(local, "session", None):
local.session = sessionmaker(bind=engine, expire_on_commit=False)()
return local.session
3、创建数据库模型基类
Base = declarative_base()
4、会话执行crud
C:
with db_session() as session:
session.add(data)
session.commit()
R:
with db_session(database=database) as session:
row = session.query(table).filter_by(id=request.id).first()
U:
with db_session(database=database) as session: count = session.query(table).filter_by(**request.filter).update(request.values) session.commit()
D:
with db_session() as session: count = session.query(table).filter_by(**request.filter).delete() session.commit()
会话除了调用固定方法外,还可以执行原生的sql语句