简体   繁体   English

Flask中的数据库迁移-SQLAlchemy

[英]database migration in flask - sqlalchemy

flask-restplus and sqlalchemy to design my backend. flask-restplus和sqlalchemy设计我的后端。 I am using flask-migrate library so that I can adjust my database tables when there is any such requirements. 我正在使用flask-migrate库,以便在有任何此类要求时可以调整数据库表。

Here is my directory structure 这是我的目录结构

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

     -wsgi.py

The code in my app.py is 我的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 file in database folder is 数据库文件夹中的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()

the __init__.py file in the database folder is 数据库文件夹中的__init__.py文件是

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


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

My thought process here is that when i run app.py then it will create the tables in my database(i have already created the database in mysql) the segment of code in app.py 我在这里的思考过程是,当我运行app.py时,它将在数据库中创建表(我已经在mysql中创建了数据库)app.py中的代码段

with flask_app.app_context():
   initDB()

when the schema changes then in that case my I will run these commands to update my databases without having to drop my database and create again. 当模式更改时,在这种情况下,我将运行这些命令来更新数据库,而不必删除数据库并重新创建。

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

But this is not working. 但这是行不通的。 I am getting a circular dependency error when i try to import app from app in the models.py 当我尝试 models.py中的应用程序导入应用程序时,出现循环依赖项错误

Please have a look into my code and tell me if my approach is correct or there is a better way to do this. 请查看我的代码,并告诉我我的方法是否正确或有更好的方法来执行此操作。 My main aim is to achieve the database migrations just like we have in django so that I can change my database schema easily. 我的主要目标是像在django中一样实现数据库迁移,以便我可以轻松更改数据库架构。

I'd suggest instantiating both app/db in app/init.py, so that app/db can be imported from a single place. 我建议在app / init.py中实例化两个app / db,以便可以从单个位置导入app / db。 After you've instantiate your manager, import the manager in run.py which is outside of the app directory and switch it between app.run()/ manager.run() 实例化管理器后,将管理器导入到app目录之外的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 项目/应用程序/ 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 项目/ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM