Python Flask-Migrate 不创建表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19323990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:26:21  来源:igfitidea点击:

Flask-Migrate not creating tables

pythonflaskflask-sqlalchemyflask-migrate

提问by Mark Richman

I have the following models in file listpull/models.py:

我在文件中有以下模型listpull/models.py

from datetime import datetime

from listpull import db


class Job(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    list_type_id = db.Column(db.Integer, db.ForeignKey('list_type.id'),
                             nullable=False)
    list_type = db.relationship('ListType',
                                backref=db.backref('jobs', lazy='dynamic'))
    record_count = db.Column(db.Integer, nullable=False)
    status = db.Column(db.Integer, nullable=False)
    sf_job_id = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False)
    compressed_csv = db.Column(db.LargeBinary)

    def __init__(self, list_type, created_at=None):
        self.list_type = list_type
        if created_at is None:
            created_at = datetime.utcnow()
        self.created_at = created_at

    def __repr__(self):
        return '<Job {}>'.format(self.id)


class ListType(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)

    def __init__(self, name):
        self.name = name

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

I call ./run.py initthen ./run.py migratethen ./run.py upgrade, and I see the migration file generated, but its empty:

我打电话./run.py init,然后./run.py migrate然后./run.py upgrade,我看到迁移文件生成,但其空:

"""empty message

Revision ID: 5048d48b21de
Revises: None
Create Date: 2013-10-11 13:25:43.131937

"""

# revision identifiers, used by Alembic.
revision = '5048d48b21de'
down_revision = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###

run.py

运行文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from listpull import manager
manager.run()

listpull/__init__.py

列表拉/__init__.py

# -*- coding: utf-8 -*-
# pylint: disable-msg=C0103

""" listpull module """

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from mom.client import SQLClient
from smartfocus.restclient import RESTClient


app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)

migrate = Migrate(app, db)

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

mom = SQLClient(app.config['MOM_HOST'],
                app.config['MOM_USER'],
                app.config['MOM_PASSWORD'],
                app.config['MOM_DB'])

sf = RESTClient(app.config['SMARTFOCUS_URL'],
                app.config['SMARTFOCUS_LOGIN'],
                app.config['SMARTFOCUS_PASSWORD'],
                app.config['SMARTFOCUS_KEY'])

import listpull.models
import listpull.views

UPDATE

更新

If I run the shell via ./run.py shelland then do from listpull import *and call db.create_all(), I get the schema:

如果我通过运行 shell./run.py shell然后执行from listpull import *并调用db.create_all(),我会得到架构:

mark.richman@MBP:~/code/nhs-listpull$ sqlite3 app.db 
-- Loading resources from /Users/mark.richman/.sqliterc
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
CREATE TABLE job (
    id INTEGER NOT NULL, 
    list_type_id INTEGER NOT NULL, 
    record_count INTEGER NOT NULL, 
    status INTEGER NOT NULL, 
    sf_job_id INTEGER NOT NULL, 
    created_at DATETIME NOT NULL, 
    compressed_csv BLOB, 
    PRIMARY KEY (id), 
    FOREIGN KEY(list_type_id) REFERENCES list_type (id)
);
CREATE TABLE list_type (
    id INTEGER NOT NULL, 
    name VARCHAR(80) NOT NULL, 
    PRIMARY KEY (id), 
    UNIQUE (name)
);
sqlite> 

Unfortunately, the migrations still do not work.

不幸的是,迁移仍然不起作用。

采纳答案by Miguel

When you call the migratecommand Flask-Migrate (or actually Alembic underneath it) will look at your models.pyand compare that to what's actually in your database.

当您调用migrateFlask-Migrate 命令(或实际上它下面的 Alembic)时,它会查看您的命令models.py并将其与数据库中的实际内容进行比较。

The fact that you've got an empty migration script suggests you have updated your database to match your model through another method that is outside of Flask-Migrate's control, maybe by calling Flask-SQLAlchemy's db.create_all().

您有一个空的迁移脚本这一事实表明您已通过 Flask-Migrate 控制之外的另一种方法更新了数据库以匹配您的模型,可能是通过调用 Flask-SQLAlchemy 的db.create_all().

If you don't have any valuable data in your database, then open a Python shell and call db.drop_all()to empty it, then try the auto migration again.

如果您的数据库中没有任何有价值的数据,请打开 Python shell 并调用db.drop_all()将其清空,然后再次尝试自动迁移。

UPDATE: I installed your project here and confirmed that migrations are working fine for me:

更新:我在这里安装了您的项目并确认迁移对我来说工作正常:

(venv)[miguel@miguel-linux nhs-listpull]$ ./run.py db init
  Creating directory /home/miguel/tmp/mark/nhs-listpull/migrations...done
  Creating directory /home/miguel/tmp/mark/nhs-listpull/migrations/versions...done
  Generating /home/miguel/tmp/mark/nhs-listpull/migrations/script.py.mako...done
  Generating /home/miguel/tmp/mark/nhs-listpull/migrations/env.pyc...done
  Generating /home/miguel/tmp/mark/nhs-listpull/migrations/env.py...done
  Generating /home/miguel/tmp/mark/nhs-listpull/migrations/README...done
  Generating /home/miguel/tmp/mark/nhs-listpull/migrations/alembic.ini...done
  Please edit configuration/connection/logging settings in
  '/home/miguel/tmp/mark/nhs-listpull/migrations/alembic.ini' before
  proceeding.
(venv)[miguel@miguel-linux nhs-listpull]$ ./run.py db migrate
INFO  [alembic.migration] Context impl SQLiteImpl.
INFO  [alembic.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate] Detected added table 'list_type'
INFO  [alembic.autogenerate] Detected added table 'job'
  Generating /home/miguel/tmp/mark/nhs-
  listpull/migrations/versions/48ff3456cfd3_.py...done

Try a fresh checkout, I think your setup is correct.

尝试重新结帐,我认为您的设置是正确的。

回答by matchew

I just encountered a similar problem. I'd like to share my solution for anyone else encountering this thread. For me, I had my models in a package. For example models/user.pyand I tried from app.models import *which did not detect anything on the migrate. However, if I changed the import to from app.models import userthis is okay why my project is young, but as I have more models a bulk import would be preferable.

我刚刚遇到了类似的问题。我想与其他遇到此线程的人分享我的解决方案。对我来说,我把我的模型放在一个包里。例如models/user.py,我尝试from app.models import *在迁移中没有检测到任何内容。但是,如果我将导入更改from app.models import user为此可以,为什么我的项目还很年轻,但是由于我有更多模型,因此最好批量导入。

回答by danidee

For anyone coming who comes across this, my problem was having

对于遇到此问题的任何人,我的问题是

db.create_all()

db.create_all()

in my main flask application file which created the new table without the knowledge of alembic

在我的主烧瓶应用程序文件中,它在不了解 alembic 的情况下创建了新表

Simply comment it out or delete it altogether so it doesn't mess with future migrations.

只需将其注释掉或完全删除它,这样它就不会影响未来的迁移。

but unlike @Miguel's suggestion, instead of dropping the whole database (i had important information in it), i was able to fix it by deleting the new table created by Flask SQLAlchemy and then running the migration.

但与@Miguel 的建议不同,我没有删除整个数据库(我在其中包含重要信息),而是通过删除由 Flask SQLAlchemy 创建的新表然后运行迁移来修复它。

and this time alembic detected the new table and created a proper migration script

这一次 alembic 检测到新表并创建了一个适当的迁移脚本

回答by wcyn

Ensure to import the Models in the manage.pyfile (or the file with the migrate instance). You have to import the models in the file, even if you are not explicitly using them. Alembic needs these imports to migrate, and to create the tables in the database. For example:

确保导入manage.py文件(或包含迁移实例的文件)中的模型。您必须导入文件中的模型,即使您没有明确使用它们。Alembic 需要这些导入来迁移和在数据库中创建表。例如:

# ... some imports ...
from api.models import User, Bucketlist, BucketlistItem # Import the models

app = create_app('dev')
manager = Manager(app)
migrate = Migrate(app, db)

manager.add_command('db', MigrateCommand)

# ... some more code here ...

if __name__ == "__main__":
    manager.run()
    db.create_all()

回答by Dany

I had the same issue but a different problem caused it. Flask-migrate workflow consists of two consequent commands:

我遇到了同样的问题,但引起了不同的问题。Flask-migrate 工作流由两个后续命令组成:

flask db migrate

which generates the migration and

产生迁移和

flask db upgrade

which applies the migration. I forgot to run the last one and tried to start next migration without applying the previous one.

这适用于迁移。我忘记运行最后一个并尝试在不应用前一个的情况下开始下一次迁移。

回答by kot_mapku3

Strange solve for me is: delete database and folder migrations. Then

对我来说奇怪的解决方法是:删除数据库和文件夹migrations。然后

>>> from app import db
>>> db.create_all()

After flask db initor python app.py db initand then flask db migrateor python app.py db migrate. Wow, It's strange, but it works for me.

之后flask db initpython app.py db init然后flask db migratepython app.py db migrate。哇,这很奇怪,但它对我有用。