第一次删除了migrate文件夹
执行upgrade 发现没有生成表,然后versions文件夹中都是空的。
alembic init --template generic migrate # 使用generic目标,创建一个migrate文件夹,并初始化。
alembic revision --autogenerate -m "initdb"
alembic revision --autogenerate -m "added user table"
alembic upgrade head #或者跟版本号
修改env.py文件如下。
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from db import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from model import * #重点1
target_metadata = Base.metadata #重点二
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
可以看下我们的目录
|-model
---- __init__.py
---- userModel.py
userModel.py 如下:
from db import Base
from sqlalchemy import Column, Integer, String,Boolean, ForeignKey
class UserModel(Base):
__tablename__ = 'user'
id = Column(Integer,primary_key=True)
username = Column(String(255),nullable=False,unique=True)
passwd = Column(String(255),nullable=False)
sex = Column(Boolean,nullable=False)
post = Column(String(100),nullable=False)
department = Column(String(200),nullable=False)
isActive = Column(Boolean,nullable=False)
roleId = Column(Integer,ForeignKey("role.id"),default=0)
def __init__(self,username,passwd,sex) -> None:
self.username = username
self.passwd = passwd
self.sex = sex
def __repr__(self) -> str:
return "<User {}>".format(self.username)
init.py如下:
from .userModel import UserModel
from .roleModel import RoleModel
db.py如下:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import Config
engine = create_engine(Config.SQLALCHEMY_DATABASE_URI,echo=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db(app):
# 在这里导入定义模型所需要的所有模块,这样它们就会正确的注册在
# 元数据上。否则你就必须在调用 init_db() 之前导入它们。
# import yourapplication.models
from model import UserModel
Base.metadata.create_all(bind=engine)