3

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?

4

1 回答 1

2

将其放在__init__.py项目文件夹下的文件中。这样,您的应用程序就变成了一个包,您可以重复使用这些变量。例如,如果您的项目名为 myproject,那么您可以

myproject/
    __init__.py
    models.py
    views.py

现在,在 models.py 等模块中,您可以这样做:

from myproject import db
于 2013-07-30T13:39:49.820 回答