烧瓶中的数据库迁移 - sqlalchemy

时间:2018-05-16 12:57:54

标签: python flask flask-sqlalchemy flask-migrate

flask-restplus和sqlalchemy来设计我的后端。 我正在使用flask-migrate库,以便在有任何此类要求时我可以调整我的数据库表。

这是我的目录结构

-mainfolder/
     -app/
         -v1/
           -app.py
           -apis/
              -__init__.py
              -some folders.
               .
               .
               .
           -database/
              -__init__.py
              -models.py
           -config/
               -__init__.py
               -detect_config_file.py
            -

     -wsgi.py

app.py 中的代码是

import logging.config
import json
import os
import sys
from flask import Flask, Blueprint
from flask_restplus import Api
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from database import *
from config.detect_config_file import config

app = Flask(__name__)
cors = CORS(app)
api = Api(version='1.0', title='Plug-n-Play APIs',
      description='Demostration of APIs behind plug-n-play dashboard')
logging_conf_path = 
 os.path.normpath(os.path.join(os.path.dirname(__file__), '../../logging.conf'))
 logging.config.fileConfig(logging_conf_path)
 log = logging.getLogger(__name__)

def configure_app(flask_app):

     flask_app.config['JWT_SECRET_KEY'] = config['JWT_SECRET_KEY']
     flask_app.config['JWT_BLACKLIST_ENABLED'] = config['JWT_BLACKLIST_ENABLED']
     flask_app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = config['JWT_BLACKLIST_TOKEN_CHECKS']
     flask_app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://'+ config['DB_USERNAME'] + ':' + config['DB_PASSWORD']+'@'+ config['DB_HOST'] + '/' + config['DB_NAME']
     flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = config['DB_TRACK_MODIFICATIONS']


def initialize_app(flask_app):
   configure_app(flask_app)

    blueprint = Blueprint('api', __name__, url_prefix='/api/v1')
    api.init_app(blueprint)

    flask_app.register_blueprint(blueprint)

    db.init_app(flask_app)

    with flask_app.app_context():
      initDB()

    jwt = JWTManager(flask_app)


def main():
  initialize_app(app)
  log.info('>>>>> Starting development server <<<<<')
  app.run(debug=config['APP_DEBUG'], host="0.0.0.0")


if __name__ == "__main__":
  main()
数据库文件夹中的

models.py 文件是

from database import db
#importing from __init__.py of database folder

from sqlalchemy.types import JSON
from sqlalchemy_utils.types.choice import ChoiceType
from config.detect_config_file import config
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app
#importing the flask app from app.py 

 db = SQLAlchemy(app)
 migrate = Migrate(app, db)

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

class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(120), unique = True, nullable = False)

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

数据库文件夹中的 __ init __。py 文件是

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def initDB():
    from database.models import *
    db.create_all()

我的思维过程就是当我运行app.py然后它将在我的数据库中创建表(我已经在mysql中创建了数据库)app.py中的代码段

with flask_app.app_context():
   initDB()

当架构发生变化时,那么在这种情况下,我将运行这些命令来更新我的数据库,而不必删除我的数据库并再次创建。

$python models.py db init
$python models.py db migrate
$python models.py db upgrade

但这不起作用。 当我在models.py

中尝试 从app中导入应用 时,我收到了循环依赖性错误

请查看我的代码并告诉我我的方法是否正确或有更好的方法来执行此操作。 我的主要目标是像在django中一样实现数据库迁移,以便我可以轻松地更改数据库模式。

1 个答案:

答案 0 :(得分:0)

我建议在app / init.py中实例化两个app / db,以便可以从一个位置导入app / db。实例化管理器后,将管理器导入到应用目录之外的run.py中,并在app.run()/ manager.run()

之间进行切换

model.py

from app import db
class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(120), unique = True, nullable = False)

project / app / init .py

def create_app():
    app = Flask(__name__)
    return app

app = create_app()
# import this db to your model.
db = SQLAlchemy(app)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

project / run.py

# Placed from app import manager right above main block.
from app import manager

if __name__ == '__main__':
    # switch between run/manager based on your need.
    #manager.run() # for DB migration
    app.run(threaded=True, debug=True)