您的位置:

flask有RuntimeError("Attempted to generate a URL without the application context being"" pushed. This has to be executed when application context is"" available.")报错是怎么回事

  发布时间:2023-02-19 08:12:08
报错的原因这个错误是由于在没有应用上下文的情况下尝试生成URL。这必须在应用程序上下文可用的情况下执行。如何解决解决方法是在生成URL的代码之前使用Flask的或app.app_context()上下文管理器。使用例子当然有,下面是一个使用Flask的上下文管理器来生成URL的例子这个例子中,在with语句块中使用url_for和url_for来生成对应视图的URL。

报错的原因

这个错误是由于在没有应用上下文的情况下尝试生成URL。这必须在应用程序上下文可用的情况下执行。通常是在没有使用Flask的app.test_request_context()或app.app_context()上下文管理器的情况下进行URL生成操作时会出现这个错误。

如何解决

解决方法是在生成URL的代码之前使用Flask的app.test_request_context()或app.app_context()上下文管理器。 例如:


with app.test_request_context():
    url = url_for('my_view')

或者


with app.app_context():
    url = url_for('my_view')

这样就可以在应用程序上下文可用的情况下生成URL了。

使用例子

当然有,下面是一个使用Flask的app.test_request_context()上下文管理器来生成URL的例子:


from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World!'

with app.test_request_context():
    print(url_for('index'))
    print(url_for('hello'))

这个例子中,在with语句块中使用url_for('index')和url_for('hello')来生成对应视图的URL。

另外,如果你的项目中使用了Flask-Script, 还可以使用manager.run()来解决上下文问题。


from flask_script import Manager

manager = Manager(app)

if __name__ == '__main__':
    manager.run()

这样就可以在应用程序上下文可用的情况下生成URL了。