2

我知道这个问题已经得到解答,但对于我的申请,我无法解决。我要做的是使用 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 从 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: Working outside of application context。这意味着应用程序当前未初始化,如果我从 app.py 导入应用程序,则会出现循环依赖项。如果我不是很清楚,我很抱歉,所以请随时询问更多细节。

4

1 回答 1

2

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

扩展程序.py

from flask_mongoalchemy import MongoAlchemy

db = MongoAlchemy()

模型.py

from extensions import db

class Person(db.Model):
    pass

烧瓶器.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()
于 2017-08-02T03:24:59.947 回答