Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask - blueprint - sqlalchemy - cannot import name 'db' into moles file

I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.

I've faced with this error:

ImportError: cannot import name 'db'

The tree of my project

nikoofar/
    run.py
    bookshelf/
        __init__.py
        mydatabase.py
        main/
            controllers.py
            __init__.py

run.py

from bookshelf import app

if __name__ == '__main__':
    app.run(debug=True, port=8000)

bookshelf / intit.py

from flask import Flask
from bookshelf.main.controllers import main
from flask_sqlalchemy import SQLAlchemy
from mydatabase import pmenu


app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy(app)
db.init_app(app)
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost/databasename'

app.config.from_object('config')

app.register_blueprint(main, url_prefix='/')

bookshelf / main / controllers.py

from flask import Blueprint
from bookshelf.mydatabase import *
from flask_sqlalchemy import SQLAlchemy


main = Blueprint('main', __name__)


@main.route('/')
def index():
    g = pmenu.query.all()
    print (g)
    return "ok"

The problem backs to from bookshelf import db, and if I delete that, the error will be changed to:

ImportError: cannot import name 'db'

bookshelf / mydatabase.py

from bookshelf import db

class pmenu(db.Model):
    __tablename__ = 'p_menu'
    id = db.Column(db.Integer, primary_key=True)
    txt = db.Column(db.String(80), unique=True)
    link = db.Column(db.String(1024))
    def __init__(self, txt, link):
        self.txt = txt
        self.link = link
    def __repr__(self):
        return "{'txt': " + self.txt + ", 'link':" + self.link + "}"

Any solution?

like image 394
niloofar Avatar asked Jan 24 '17 12:01

niloofar


People also ask

Why can’t I create a database in flask?

The reason for this is that when we create our database, flask will not be able to access the database models in our models.py file. Unless we draw it back into the app initialization file for the database object to be aware of its existence. At this point, your __init__.py file should look like this:

How do I use SQLAlchemy in flask?

To work with SQLAlchemy, we need to install the SQLAlchemy library first. With SQLAlchemy installed, we have to import the SQLAlchemy class from the flask_sqlalchemy module into the main application file ( __init__.py) of our project.

Is it safe to use a circular import in flask?

Be wary of circular imports in Flask and in Python in general. This is, in user.py there is an import of db from ../__init__.py but in that file there is an import of User happening before the definition of db.

How to write SQL queries in Flask web applications?

In Flask web applications, to manipulate databases, we can use SQL and Object Relational Mapping (ORM). An ORM makes writing SQL queries easier for a programmer, because it enables us to write queries in an object-oriented language, and then ORM automatically translates it to SQL and retrieves the result as an object.


1 Answers

This is actually a simple, yet frustrating issue. The problem is you are importing main BEFORE you are creating the instance of db in your __init__.py

If move the import to after your db = SQLAlchemy(app), it will work:

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://uername:password@localhost/test'

db = SQLAlchemy(app)

from bookshelf.main.controllers import main #<--move this here

app.register_blueprint(main, url_prefix='/')
like image 87
CodeLikeBeaker Avatar answered Oct 24 '22 10:10

CodeLikeBeaker