0
votes

Here the problem is that I am trying to use my db connection in my blueprints, but I cannot seem to avoid an importation error despite my efforts to import. Here is my original question:

Blueprints, PyMongo in Flask

There is a suggestion from the original poster at: Circular import of db reference using Flask-SQLAlchemy and Blueprints, but there has to be an easier way of doing things.

I've tried the suggestion in my original question which leads to the importation error when trying to pull in the mongo connection in my blueprint. The error is:

ImportError: cannot import name 'mongo'

I've also tried moving the import location so its after the db connection in my login.py, however none of this seems to work. Where can I find a simple working example that I can use that appears to be bulletproof.

1

1 Answers

1
votes

Circular references can be avoid by moving out the dependency away.

Common circular reference scenario:

A.py:

import B
def dependency():
    pass

B.py:

from A import dependency

Can be avoided by refactoring as:

A.py:

import B
from C import dependency

B.py:

from C import dependency

C.py:

def dependency():
    pass

The error: ImportError: cannot import name 'mongo'
Suggest that you file cannot find the module mongo.

To solve that, ensure the module path is correct and that any folder have a __init__.py file in it.

Also from you previous question, notice that you can attach your instancied mongo variable to your flask application, then when using current_app you will get your db connection.

app = Flask(__name__)
app.mongo = PyMongo(app)