SwiftCaller
SwiftCaller

Reputation: 45

Avoiding circular imports Python

I know this question have already been answered, but for my application, I can't resolve it. What I'm trying to do is to setup a database using MongoAlchemy instead of using MongoClient. I want to have diffrent scripts for every operation This is my main file, 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'] = '[email protected]'
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)

Note that I'm modyfing on the old version, so the imports are still there. The problem with the circular imports appear when I try do import app from app.py into the script which initializes the database, described below:

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

If I try to use current_app I get the error: RuntimeError: Working outside of application context. which means that the app is not currently initialized, and if I import the app from app.py the circular dependency appears. I'm sorry if I wasn't pretty clear, so feel free to ask for more details.

Upvotes: 3

Views: 515

Answers (1)

DobleL
DobleL

Reputation: 3918

I like to place all extensions on a extensions.py file and create a function to initialize and configurate the app instance

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

Upvotes: 3

Related Questions