Flash messaging not working in Flask

我怕爱的太早我们不能终老 提交于 2020-07-09 10:14:35

问题


I have been unable to get the flash function to work in flask. Heres my code.

#!venv/bin/python3
from flask import Flask, flash

app = Flask(__name__)
app.config['SECRET_KEY'] = '12345'

@app.route('/')
def index():
    flash('Hi')
    return 'Hello'

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

I expected this to flash a message saying hi but when I load the page no flash box appears. What am I not understanding here?


回答1:


I think the main problem is that you're returning a string and not a render_template that handles the flash and converts it to a display message. Check out this documentation code here for an example of how to handle flashes

So I suggest trying: return render_template('index.html')

And then use the index.html file to set up your code that handles the flash message. I have a feeling that just returning a string, as you've done here, without somewhere for the code to understand the flash will give a null result.




回答2:


It has been a while since the question was asked. I'll post my answer here since I got to this question somehow.

As Miguel Grinberg wrote in "Flask Web Development: Developing Web Applications with Python":

Calling flash() is not enough to get messages displayed; the templates used by the application need to render these messages.

So anyone who have the same problem, just ensure, that you added the get_flashed_messages() function to the template and then displayed a message. For the reference you can look at:

Python Flask flash not working correctly,

and for sure Miguel Grinberg's book mentioned above, Chapter 4.

Hope this will be helpful.



来源:https://stackoverflow.com/questions/48847430/flash-messaging-not-working-in-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!