避免循环导入Python

时间:2017-08-01 09:08:17

标签: python flask circular-dependency mongoalchemy

我知道这个问题已经得到解答,但对于我的申请,我无法解决。我想要做的是使用MongoAlchemy而不是使用MongoClient来设置数据库。我想为每个操作都有不同的脚本这是我的主文件,app.py:

import os

from flask import Flask, jsonify
from blueprints.db import insert_db
from blueprints.delete_blueprint import delete_bp
from blueprints.insert_blueprint import insert_bp
from blueprints.read_blueprint import read_bp
from blueprints.login_update_blueprint import log_update
import traceback

app = Flask(__name__)

app.register_blueprint(log_update)
app.register_blueprint(read_bp)
app.register_blueprint(insert_bp)
app.register_blueprint(delete_bp)

# database configuration
app.config['MONGOALCHEMY_DATABASE'] = 'rest_api'

# populate table with initial values
insert_db.populateTables()

# mail configuration
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'chis.simion12@gmail.com'
app.config['MAIL_PASSWORD'] = ''
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True


@app.errorhandler(404)
def page_not_found(c):
    return 'The required page does not exist'


@app.errorhandler(400)
def bad_req(c):
    return 'Bad request. Please review the request'


@app.errorhandler(Exception)
def handle_Exception(error):
    print("\n ______ ERROR ______\n")
    print(traceback.format_exc())
    print("_____________________\n")

    response = dict()
    response['message'] = "A PROBLEM HAS OCCURED, PLEASE TRY AGAIN LATER"
    response['status_code'] = 500
    response = jsonify(response)
    response.status_code = 500

    return response


if __name__ == '__main__':
    app.secret_key = os.urandom(12)
    app.run(debug=True, threaded=True)

请注意,我正在使用旧版本,因此导入仍然存在。当我尝试将应用程序从app.py导入初始化数据库的脚本时,会出现循环导入的问题,如下所述:

from flask import current_app
from flask_mongoalchemy import MongoAlchemy
# from app import app

db = MongoAlchemy(current_app)


class People(db.Document):
    Name = db.StringField()
    Age = db.IntField()
    Password = db.StringField()
    Vms = db.AnythingField()

如果我尝试使用current_app,我会收到错误: RuntimeError:在应用程序上下文之外工作。表示该应用程序当前未初始化,如果我从app.py导入应用程序出现循环依赖。如果我不是很清楚,我很抱歉,请随时询问更多细节。

1 个答案:

答案 0 :(得分:1)

我喜欢将所有扩展名放在extensions.py文件上并创建一个函数来初始化和配置应用程序实例

extensions.py

from flask_mongoalchemy import MongoAlchemy

db = MongoAlchemy()

models.py

from extensions import db

class Person(db.Model):
    pass

flaskr.py

from flask import Flask
from extensions import db

def create_app():
    app = Flask(__name__)
    db.init_app(app)

    return app

app = create_app()
app.run()