这段代码会报错Working outside of application context.
时间: 2023-09-26 16:13:54 浏览: 51
这个错误通常是在应用程序上下文外部使用了 Flask 扩展对象的时候出现的。在 Flask 中,应用程序上下文是指在请求期间 Flask 执行的活跃区域。要解决这个问题,您需要确保在应用程序上下文中使用 Flask 扩展对象。
在上面的代码中,您需要在执行 db.drop_all() 和 db.create_all() 前调用 app.app_context(),以确保在应用程序上下文中使用 db 对象。例如,可以将以下代码添加到您的代码中:
```
with app.app_context():
db.drop_all()
db.create_all()
```
这将在应用程序上下文中执行这些操作,从而避免报错。
相关问题
RuntimeError: Working outside of application context.
This error occurs when you are trying to access or modify data that is tied to the Flask application context, but you are not currently within that context.
For example, if you try to access a Flask extension or request data outside of a Flask route function, you may encounter this error.
To resolve this error, you need to make sure that you are operating within the Flask application context. This can be achieved by wrapping your code within a Flask route function or by using the `with app.app_context()` block.
Here's an example of using `with app.app_context()`:
```python
from flask import Flask
app = Flask(__name__)
with app.app_context():
# your code that requires the Flask application context here
```
Alternatively, you can also use the `current_app` proxy object from the `flask` module to access the Flask application context from within your code:
```python
from flask import current_app
# your code that requires the Flask application context here
current_app.some_extension.do_something()
```
Remember to always make sure you are within the Flask application context before accessing or modifying any data related to your Flask application.
flask raise RuntimeError(unbound_message) from None RuntimeError: Working outside of application context.
这个错误通常发生在 Flask 应用程序上下文之外的代码中尝试访问 Flask 应用程序上下文时。在 Flask 中,应用程序上下文是 Flask 应用程序运行时的环境。为了解决这个问题,你需要在访问 Flask 应用程序上下文之前,先激活应用程序上下文。可以通过将你的代码放在 Flask 应用程序的请求上下文中来实现这一点,或者使用 Flask 提供的上下文管理器,例如 `app.app_context()`。具体实现方式可以参考 Flask 官方文档中的相关章节。