Alembic反相升级/降级Flask-SQLAlchemy 关于您的代码

如何解决Alembic反相升级/降级Flask-SQLAlchemy 关于您的代码

我最近一直在和Alembic斗争,我不知道为什么它会颠倒正确的升级/降级更改。

我在用户模型中创建了2个新字段(about_me,last_seen),运行“ flask db migration”,然后查看版本文件,可以看到正确的迁移是降级而不是升级。

我尝试运行db.create_all,db.drop_all,删除alembic_version表但未成功。每次下面的结果相同时,我应该将DROP_TABLE命令降级,将CREATE_TABLE命令降级。

我目前能够使之正常工作的唯一方法是删除所需的表,然后手动将代码从降级复制并粘贴到升级。

迁移文件:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('tutor_category')
    op.drop_table('tutors')
    op.drop_index('ix_categories_name',table_name='categories')
    op.drop_table('categories')
    op.drop_index('ix_users_email',table_name='users')
    op.drop_index('ix_users_first_name',table_name='users')
    op.drop_index('ix_users_last_name',table_name='users')
    op.drop_index('ix_users_timestamp_joined',table_name='users')
    op.drop_table('users')
    op.drop_index('ix_reviews_rating',table_name='reviews')
    op.drop_index('ix_reviews_timestamp',table_name='reviews')
    op.drop_table('reviews')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('reviews',sa.Column('id',sa.INTEGER(),autoincrement=True,nullable=False),sa.Column('user_id',autoincrement=False,nullable=True),sa.Column('tutor_id',sa.Column('rating',sa.Column('timestamp',postgresql.TIMESTAMP(),sa.ForeignKeyConstraint(['tutor_id'],['tutors.id'],name='reviews_tutor_id_fkey'),sa.ForeignKeyConstraint(['user_id'],['users.id'],name='reviews_user_id_fkey'),sa.PrimaryKeyConstraint('id',name='reviews_pkey')
    )
    op.create_index('ix_reviews_timestamp','reviews',['timestamp'],unique=False)
    op.create_index('ix_reviews_rating',['rating'],unique=False)
    op.create_table('users',server_default=sa.text("nextval('users_id_seq'::regclass)"),sa.Column('first_name',sa.VARCHAR(length=64),sa.Column('last_name',sa.Column('email',sa.VARCHAR(length=120),sa.Column('profile_img',sa.Column('password_hash',sa.VARCHAR(length=128),sa.Column('timestamp_joined',sa.Column('about_me',sa.VARCHAR(length=140),sa.Column('last_seen',postgresql.TIMESTAMP(timezone=True),name='users_pkey'),postgresql_ignore_search_path=False
    )
    op.create_index('ix_users_timestamp_joined','users',['timestamp_joined'],unique=False)
    op.create_index('ix_users_last_name',['last_name'],unique=False)
    op.create_index('ix_users_first_name',['first_name'],unique=False)
    op.create_index('ix_users_email',['email'],unique=True)
    op.create_table('categories',server_default=sa.text("nextval('categories_id_seq'::regclass)"),sa.Column('name',name='categories_pkey'),postgresql_ignore_search_path=False
    )
    op.create_index('ix_categories_name','categories',['name'],unique=False)
    op.create_table('tutors',server_default=sa.text("nextval('tutors_id_seq'::regclass)"),sa.Column('price',postgresql.DOUBLE_PRECISION(precision=53),name='tutors_user_id_fkey'),name='tutors_pkey'),postgresql_ignore_search_path=False
    )
    op.create_table('tutor_category',sa.Column('category_id',sa.ForeignKeyConstraint(['category_id'],['categories.id'],name='tutor_category_category_id_fkey'),name='tutor_category_tutor_id_fkey'),sa.PrimaryKeyConstraint('tutor_id','category_id',name='tutor_category_pkey')
    )
    # ### end Alembic commands ###

Models.py

class Users(UserMixin,db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key=True)
    first_name = db.Column(db.String(64),index=True,nullable=False)
    last_name = db.Column(db.String(64),nullable=False)
    email = db.Column(db.String(120),unique=True,nullable=False)
    profile_img = db.Column(db.String(120),nullable=True)
    password_hash = db.Column(db.String(128),nullable=False)
    timestamp_joined = db.Column(db.DateTime,default=datetime.utcnow)
    about_me = db.Column(db.String(140),nullable=True)
    last_seen = db.Column(db.DateTime(140),default=datetime.utcnow)

    def set_password(self,password):
        self.password_hash = generate_password_hash(password)

    def check_password(self,password):
        return check_password_hash(self.password_hash,password)
    
    def avatar(self):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon'.format(
        digest)

    def __repr__(self):
        return '<User {}>'.format(self.username)

class Tutors(db.Model):
    __tablename__ = 'tutors'
    id = db.Column(db.Integer,primary_key=True)
    user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
    price = db.Column(db.Float)

    # Connecting this field to the association table. 
    category = db.relationship("Categories",secondary="tutor_category")

    def __repr__(self):
        return '<Tutor id {}'.format(self.user_id) + ',price {}>'.format(self.price)

class Reviews(db.Model):
    __tablename__ = 'reviews'
    id = db.Column(db.Integer,db.ForeignKey('users.id'))
    tutor_id = db.Column(db.Integer,db.ForeignKey('tutors.id'))
    rating = db.Column(db.Integer,index=True)
    timestamp = db.Column(db.DateTime,default=datetime.utcnow)

    def __repr__(self):
        return '<Review User: {}'.format(self.user_id) + ' Tutor: {}'.format(self.tutor_id) + ' Rating: {}>'.format(self.rating)

class Categories(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),index=True)
    # Connecting this field to the association table. 
    tutor = db.relationship('Tutors',secondary="tutor_category")

    def __repr__(self):
        return '<Category {}>'.format(self.name)

# Declaring the association table
tutor_category = db.Table('tutor_category',db.Column('tutor_id',db.Integer,db.ForeignKey('tutors.id'),primary_key=True),db.Column('category_id',db.ForeignKey('categories.id'),primary_key=True)
)

@login.user_loader
def load_user(id):
    return Users.query.get(int(id))

Manage.py

from flask import Flask
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from flask_sqlalchemy import SQLAlchemy
from app import app
from app import models

db = SQLAlchemy(app)

POSTGRES = {
    'user': 'richard','pw': 'richard2906','db': 'codetutors','host': 'localhost','port': '5432',}

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\
%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

migrate = Migrate(app,db)
manager = Manager(app)
db.init_app(app)

manager.add_command('db',MigrateCommand)

def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\
    %(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    db.init_app(app)
    return app

if __name__ == '__main__':
    manager.run()

env.py

from __future__ import with_statement

import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context
from manage import db



# 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.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support

# from app.models import Users,Tutors,Categories,Reviews
target_metadata = db.metadata

# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
    'sqlalchemy.url',str(current_app.extensions['migrate'].db.engine.url).replace('%','%%'))
target_metadata = current_app.extensions['migrate'].db.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
    )

    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.

    """

    # this callback is used to prevent an auto-migration from being generated
    # when there are no changes to the schema
    # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
    def process_revision_directives(context,revision,directives):
        if getattr(config.cmd_opts,'autogenerate',False):
            script = directives[0]
            if script.upgrade_ops.is_empty():
                directives[:] = []
                logger.info('No changes in schema detected.')

    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,process_revision_directives=process_revision_directives,**current_app.extensions['migrate'].configure_args
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

感谢您的帮助

解决方法

我只是猜测,当您移至flask db migrate而不是将flask_scriptpython3 migrate.py db migrate一起使用时,您的数据库也已更改。

看来,您的数据库(在提出问题时)已经包含要迁移的表。当它们存在但未在代码中使用/提及/导入时,显然是从Alembic删除它们的正确决定。

从这个角度来看,升级应删除表,降级后将重新创建它们。

始终在迁移脚本中导入模型(使用flask_script时),并始终使用db upgrade命令应用数据库更改,而不是自己添加表。 >

这应该导致正确的升级脚本。

关于您的代码

  • 您可以创建自己的app而不是将其导入
  • 您已使用导入的app变量绑定SQLAlchemy实例,但是还定义了另一个未使用的create_app函数?而且您也对该实例执行了db.init_app(app)(即使它是由SQLAlchemy(app)
  • 创建的)

我想这会使Alembic转向错误的app上下文,在该上下文中没有定义您的模型。另外,您的数据库包含此app中未提及的表。

这是我的migration.py:

from flask import Flask
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from models import * # contains 'db.Model' classes and instance of 'db'

app = Flask(__name__)
config_path = "config.json"
app.config.from_json(config_path)

# db = SQLAlchemy(app) # <-- the "normal way"
db.init_app(app) # <-- most likely if you have defined 'db' already in 'models.py'

migrate = Migrate(app,db)
manager = Manager(app)
manager.add_command('db',MigrateCommand)

if __name__ == '__main__':
    manager.run()
,

对于那些遇到类似问题的人,我使用Flask-Script Manager作为“ python manage.py db migration”,然后更改为“ flask db migration”,并且应用程序开始正确识别模型/表。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-