在重构代码时烧瓶 - 迁移问题

问题描述 投票:0回答:1

我使用flask-migrate为Python-Flask应用程序提供了以下文件结构:

File Structure

我的问题是

1 - 我无法在manage.py中使用db和create_app

当我做:

$ python manage.py db init

我得到以下错误:

File "/app/main/model/model.py", line 25, in <module>
    class User(db.Model):
NameError: name 'db' is not defined

(db在main.init.py中定义)

我尝试了不同的选择但没有成功。

我想将manage.py,model.py和main.init.py保存在单独的文件中。

2-在模型.py中我将需要db。我如何使db可用于model.py?

以下是manage.py

# This file take care of the migrations
# in model.py we have our tables
import os
import unittest

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

from app.main import create_app
from app.main import db
# # We import the tables into the migrate tool
from app.main.model import model


app = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')

app.app_context().push()

manager = Manager(app)

migrate = Migrate(app, db)

manager.add_command('db', MigrateCommand)

#### If I add  model.py here all should be easier , but still I have the 
#### issue with 
#### from app.main import create_app , db


@manager.command
def run():
    app.run()


@manager.command
def test():
    """Runs the unit tests."""
    tests = unittest.TestLoader().discover('app/test', pattern='test*.py')
    result = unittest.TextTestRunner(verbosity=2).run(tests)
    if result.wasSuccessful():
        return 0
    return 1

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

这是app.init.py,其中定义了db和create_app

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_cors import CORS

from .config import config_by_name

from flask_restful import Resource, Api
# from flask_restplus import Resource
from app.main.controller.api_controller import gconnect, \
     showLogin, createNewTest, getTest, getTests, getIssue, createNewIssue

db = SQLAlchemy()
flask_bcrypt = Bcrypt()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    cors = CORS(app,
                supports_credentials=True,
                resources={r"/api/*":
                           {"origins":
                            ["http://localhost:3000",
                             "http://127.0.0.1:3000"]}})
    api = Api(app)
    db.init_app(app)
    flask_bcrypt.init_app(app)

    api.add_resource(gconnect, '/api/gconnect')
    api.add_resource(showLogin, '/login')
    api.add_resource(createNewTest, '/api/test')
    api.add_resource(getTest, '/api/test/<int:test_id>')
    api.add_resource(getTests, '/api/tests')
    api.add_resource(getIssue, '/api/issue/<int:issue_id>')
    api.add_resource(createNewIssue, '/api/issue')

    return app

这是我的模型(简单来说就是其中一个)

from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.sql import func


# # # This will let sql alchemy know that these clasess
# # # are special Alchemy classes
# Base = declarative_base()



class User(db.Model):

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False)
    email = db.Column(db.String(250), nullable=False)
    pictures = db.Column(db.String(250))
    role = db.Column(db.String(25), nullable=True)

我的问题是:

1 - 我无法在manage.py中使用db和create_app

当我做:

$ python manage.py db init

我得到以下错误:

文件“/app/main/model/model.py”,第25行,类User(db.Model):NameError:name'db'未定义

(db在main.init.py中定义)

我尝试了不同的选择但没有成功。

我想将manage.py,model.py和main.init.py保存在单独的文件中。

2-在模型.py中我将需要db。我如何使db可用于model.py?

python python-3.x flask-sqlalchemy factory-pattern flask-migrate
1个回答
0
投票

一个简单的解决方案是创建一个除__init__.py之外的单独初始化文件。例如init.py在哪里初始化sqlalchemy以及其他扩展。这样,它们可以在所有模块中导入,而不会出现任何循环依赖性问题。

然而,更优雅的解决方案是使用Flask的current_appg代理。它们是为了帮助Flask用户避免循环依赖的任何问题。

通常,您在app模块中初始化烧瓶__init__.py,而__init__.py模块有时必须从其子模块导入一些变量。当子模块尝试导入初始化扩展时,这会成为问题

作为一般经验法则,外部模块应该从它们的子模块导入而不是相反。

所以这是解决问题的一种方法(引自here):

** __init__.py

from flask import g

def get_db():
    if 'db' not in g:
        g.db = connect_to_database()

    return g.db

@app.teardown_appcontext
def teardown_db():
    db = g.pop('db', None)

    if db is not None:
        db.close()


def init_db():
    db = get_db()

现在,您可以通过以下方式轻松将数据库连接导入任何其他模块

from flask import g

db = g.db
db.do_something()
© www.soinside.com 2019 - 2024. All rights reserved.