Lee White
Lee White

Reputation: 3739

In Flask-SQLAlchemy, where do I initialise and store the database object?

I am building a website using Flask and SQLAlchemy in Python, and having great fun so far.

There is something I'm not sure about, however. The following code is used to connect to the database:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'bla'
db = SQLAlchemy(app)

How do I reuse this object in different files, though? I have tried storing it in g, but this causes problems in the database models, when I try to use the database outside a web request's scope. Is there a standard method to make db accessible in multiple files/classes?

Upvotes: 3

Views: 1116

Answers (1)

codegeek
codegeek

Reputation: 33349

Put it in a __init__.py file under your project folder. This way, your application becomes a package and you can re-use the variables. For example, if your project is called myproject, then you could have

myproject/
    __init__.py
    models.py
    views.py

Now, in modules such as models.py, you can just do:

from myproject import db

Upvotes: 2

Related Questions