gpt4 book ai didi

python - 避免循环导入 Python

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:47 25 4
gpt4 key购买 nike

我知道这个问题已经有人回答了,但是对于我的申请,我无法解决它。我想要做的是使用 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: Working out of application context. 这意味着该应用程序当前未初始化,如果我从 app.py 导入应用程序出现循环依赖。很抱歉,如果我不是很清楚,请随时询问更多详细信息。

最佳答案

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

扩展.py

from flask_mongoalchemy import MongoAlchemy

db = MongoAlchemy()

模型.py

from extensions import db

class Person(db.Model):
pass

flask .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()

关于python - 避免循环导入 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45433575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com