flask-migrate 数据库迁移初始化报错

点点乐淘淘
  • 332

flask-migrate 数据库迁移初始化报错,报错信息如下图:
图片描述

代码结构如下:
图片描述

config.py代码

# 配置文件
import os
DEBUG = True
# dialect+driver://username:[email protected]:port/database # 链接格式
DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSRORD = ''
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'migrate_demo'

# 随机字符串,一般用random自动生成
SECRET_KEY = os.urandom(24)
# 当设置session.permanent = True时,下面的参数将决定有效期多久
PERMANENT_SESSION_LIFETIME = 7

SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(DIALECT, DRIVER, USERNAME, PASSRORD, HOST, PORT, DATABASE)

SQLALCHEMY_TRACK_MODIFICATIONS = False

exts.py代码:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

manage.py代码:

from flask_script import Manager
from migrate_demo import app
from flask_migrate import Migrate, MigrateCommand
from exts import db
from models import Article

manager = Manager()

# 1. 要使用flask_migrate,必须绑定app和db
migrate = Migrate(app, db)

# 2. 把MigrateCommand命令添加到manager中
manager.add_command("db", MigrateCommand)

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

migrate_demo.py代码:

from flask import Flask
from exts import db
import config

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)

# with app.app_context():
#     db.create_all()


@app.route('/')
def hello_world():
    return 'Hello World!'


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

models.py代码:

from exts import db
from migrate_demo import app


class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    # tags = db.Column(db.Text, nullable=False)


@app.route("/inster")
def inster():
    a1 = Article(title='aaa', content="aacontent")
    a2 = Article(title="bbb", content="bbcontent")
    db.session.add(a1)
    db.session.add(a2)
    db.session.commit()
    return 'inster'


@app.route('/select')
def select():
    result = Article.query.filter(Article.title == "aaa").first()
    print("title: %s, content: %s" % (result.title, result.content))

求高手帮忙

回复
阅读 2.6k
2 个回答

你在创建SQLAlchemy以及Manager对象的时候,没有将app传递给它们。
exts.py中,将db = SQLAlchemy()改为db = SQLAlchemy(app)
manage.py中,将manager = Manager()改为manager = Manager(app)
应该就可以了。

解决了,manage.py中manager = Manager()改成manager = Manager(app)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏