简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM