【配置sqlalchemy】配置orm并且迁移数据表
1:目录结构
2:配置sqlalchemy参数文件 : config.py
# config.py
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker #数据库访问地址 SQLALCHEMY_DATABASE_URL = "sqlite:///./database/app.sqlite3" # SQL # SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" # MYSQL #启动引擎 engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) #启动会话 SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) #数据模型的基类 Base = declarative_base()
3:添加表模型文件: model.py
#model.py
from sqlalchemy import Boolean, Column, Integer, String, create_engine from .config import Base # 用户信息 class UserInfo(Base): __tablename__="userinfo" id = Column(Integer, primary_key=True,index=True,autoincrement=True) # autoincrement自增长 index索引 username = Column(String,unique=True,nullable=True,index=True,comment="用户名") # nullable不能为空 name = Column(String(10),unique=True,index=True) phone = Column(String,unique=True,index=True) age = Column(Integer,nullable=True,) sex = Column(Integer,nullable=True,) is_active = Column(Boolean, default=True) def __repr__(self): return self.username
4:更新、迁移数据库
1: 终端安装alembic : pip install alembic 2:终端初始化alembic : alembic init alembic 3:将alembic.ini中的sqlalchemy.url改为你数据库地址: sqlalchemy.url = sqlite:///./database/app.sqlite3 (要与./database/config.py配置的一样) 4:找到alembic文件夹下的env.py,找到target_metadata = None
替换: import sys from os.path import abspath, dirname from database.model import Base # 这里是Base是model.py模板里面的BASE # 告诉alembic 你的表数据在哪 sys.path.append(dirname(dirname(abspath(__file__)))) target_metadata = Base.metadata
PS:到此为止配置成功!
两行迁移命令: 1:alembic revision --autogenerate -m "自定义迁移文件名" 2:alembic upgrade head
5:ORM的使用
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine # 导入基类 from config import SQLALCHEMY_DATABASE_URL # 启动会话 engine = create_engine(SQLALCHEMY_DATABASE_URL) Session = sessionmaker(bind=engine) session = Session() # 导入表 import model user_add = model.UserInfo(username="wanghong", name="WH", phone="10086", age=15) session.add(user_add) session.commit()
ORM常用使用方法传送门:https://www.cnblogs.com/wanghong1994/p/13742270.html
Python全栈(后端、数据分析、脚本、爬虫、EXE客户端) / 前端(WEB,移动,H5) / Linux / SpringBoot / 机器学习