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-20 19:38:40 浏览: 275
这个错误通常是因为在使用 Flask 和 SQLAlchemy 时没有正确初始化 SQLAlchemy 实例。你应该在创建 SQLAlchemy 实例后,调用 `init_app` 方法将其绑定到 Flask 应用程序上下文中。示例如下:
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy()
def create_app():
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db.init_app(app)
# ... 其他 Flask 初始化代码 ...
return app
```
如果你已经调用了 `init_app` 方法,那么可能是你创建了多个 SQLAlchemy 实例,需要检查并确保只有一个实例与 Flask 应用程序相关联。
相关问题
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.
阅读全文