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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With