Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flash messaging not working in Flask

Tags:

python

flask

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?

like image 768
William234234 Avatar asked Feb 18 '18 00:02

William234234


People also ask

Why is Flash not working Flask?

Now if you try to run the code right away, you'll get an error such as: “RuntimeError RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.” So in order to use flash messages in Flask, you need a secret key to be set.

How do I show flash messages in Flask?

The flash() method is used to generate informative messages in the flask. It creates a message in one view and renders it to a template view function called next. In other words, the flash() method of the flask module passes the message to the next request which is an HTML template.

How do I clear flash messages on Flask?

In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages() . Changed in version 0.3: category parameter added. Parameters: message – the message to be flashed.

How do I change my secret key on Flask?

Generate the Secret Key Using Different Ways in Flask and Python. To access a session ID, you need to use an encryption key assigned to the SECRET_KEY variable, so at the time, we set the value of the SECRET_KEY variable as a string is extremely dangerous. This key needs to be randomly generated.


1 Answers

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.

like image 127
PeptideWitch Avatar answered Nov 05 '22 23:11

PeptideWitch