RuntimeError: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
时间: 2024-03-23 07:37:50 浏览: 457
这个错误是由于Flask app没有正确注册到SQLAlchemy实例所引起的。有两种可能的原因:
1. 您可能没有在Flask app中调用SQLAlchemy的init_app()方法。在您的Flask应用程序中,您需要使用app.config属性来设置SQLAlchemy的配置,然后调用SQLAlchemy的init_app()方法,以便将其与Flask应用程序关联起来。例如:
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy()
db.init_app(app)
```
2. 另一个可能的原因是您创建了多个SQLAlchemy实例。如果您创建了多个SQLAlchemy实例并尝试在不同的应用程序上下文中使用它们,则可能会出现此错误。请确保在应用程序中只创建一个SQLAlchemy实例,并在需要时将其传递给其他部分。
相关问题
File E:\python3.7.7\lib\site-packages\flask_sqlalchemy\extension.py, line 308, in init_app Either SQLALCHEMY_DATABASE_URI or SQLALCHEMY_BINDS must be set. RuntimeError: Either SQLALCHEM
Y_DATABASE_URI or SQLALCHEMY_BINDS must be set is a common error in Flask-SQLAlchemy. This error is raised when the Flask application is not configured properly to use SQLAlchemy.
To fix this error, you need to set the SQLALCHEMY_DATABASE_URI configuration variable in your Flask application configuration. This variable should contain the connection string for your database.
Here is an example of how to set the SQLALCHEMY_DATABASE_URI variable:
```
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@localhost/mydatabase'
```
You can also set the SQLALCHEMY_BINDS variable if you need to connect to multiple databases.
Once you have set the configuration variables, you should be able to initialize the Flask-SQLAlchemy extension without any errors.
阅读全文