Trying to flash a message raises an exception - python

I want to use flash to show a message, but doing so raises an exception. The code below demonstrates the error, and works fine if the call to flash is removed. How do I fix this error?
from flask import Flask, flash
app = Flask(__name__)
#app.route('/')
def index():
flash('Entered')
return 'Completed'
app.run(debug=True)
RuntimeError: the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.

As the error says, you have not set a secret key, so the session is unavailable. The session relies on a secret key to sign the cookie prevent tampering. Message flashing relies on the session.
Set the SECRET_KEY config item to fix this error.
# set as part of the config
SECRET_KEY = 'many random bytes'
# or set directly on the app
app.secret_key = 'many random bytes'

In your run.py file
from tc import app
app.secret_key='12345'
app.run(debug=True)

Related

Flask session object does not persist between requests despite hardcoded secret key

I am currently running into an issue deploying a Flask app on Amazon's EB2 service. The Flask app works locally. When it is deployed, however, it only works for the first person who clicks the link. After that it throws the following error:
Internal Server Error The server encountered an internal error and was
unable to complete your request. Either the server is overloaded or
there is an error in the application.
The error it is throwing out concerns the Flask session - it becomes empty after routing from one site to another. I also noticed that the before_first_request function detailed below is ran only once, for the first user, and never again - which is even more bewildering.
Here's the minimal example:
from flask import Flask, render_template, request, session, url_for
application = Flask(__name__)
application.secret_key = "mysecretkey"
#application.before_first_request
def before_first_request():
""" these commands are run before the first request"""
# setup logging
application.logger.setLevel(logging.INFO)
application.logger.info('starting up Flask')
# clear session
session.clear()
# load in PID
session['pid'] = 123
# add parameters to the session
params = dict()
params['parameter'] = 0
session['params'] = params
application.logger.info(session) # it is printing the session as expected
return 'OK'
#application.route('/')
def main():
""" landing page """
application.logger.info(session) # empty
application.logger.info(application.secret_key) # as expected
params, results = session.pop('params'), session.pop('results') # throws out the error
return render_template('empty_template.jinja', args = session)
I am wondering if anyone might know what is going on how to resolve the issue?
I managed to solve it.
The error was that #before_first_request wrapper actually only ran once before first request ever made to the app. Hence, the session was actually only created and populated once.
I fixed that error by adding the call to before_first_request function at the top of the main function.

Cannot create secret key in flask; returns “name 'session' is not defined”

Im attempting to create a website in flask. To do that, I need use sessions and therefore I am required to use a secret key. I did all of that, and yet it still returns a long error log with
nameerror: name ‘session’ is not defined at then end
I tried everything and moved the thing that sets the secret key everywhere, but it always had the same issue. Here is my code currently:
from flask import Flask
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
usernumber = 0
#app.route('/')
def homepage():
global usernumber
session['usernumber'] = usernumber
usernumber = usernumber + 1
Usernumberstring = session['usernumber']
return f"Welcome {Usernumberstring}"
if __name__ == '__main__':
app.run(use_reloader=True, debug=False, host="0.0.0.0")
You are not importing session;
from flask import Flask, session
Check more details about flask session here;
https://pythonbasics.org/flask-sessions/#:~:text=Unlike%20cookies%2C%20Session%20(session),temporary%20directory%20on%20the%20server.

Accessing Flask Session From Different Files

I'm trying to neatly compartmentalize my code by separating flask app, service component and a decoupled key/value pair store.
My web app looks like this:
import flask
import os
import service_component as service
app = flask.Flask(__name__)
#app.route("/", methods=["POST"])
def event():
service.dostuff()
return "ok", 200
if __name__ == "__main__":
app.run(port=5000, debug=True)
# for test purposes
app.secret_key = os.urandom(24)
My service_component is:
import key_value_store
def dostuff():
val_i_want = key_value_store.provider["key"]
...and key_value_store looks like:
from flask import session
class SessionProvider:
def __getitem__(self, key):
return session.get(key)
def __setitem__(self, key, value):
session[key] = value
provider = SessionProvider()
The problem is that when I run the program, I get the error:
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
Is there some requirement to keep the usage of "session" in my web app file? Are there recommended ways around this that still let me maintain loose coupling of components/abstraction of the key/value pair store?
Don't set the secret key here:
if __name__ == "__main__":
app.secret_key = os.urandom(24)
app.run(port=5000, debug=True)
return "ok", 200 # Also this does nothing here
The above will only apply when running with python app.py not with flask run or a WSGI server.
Also this would change the secret key on each launch, which you want to avoid. You should really be loading a pre-defined key in via your config, so user cookies aren't invalidated on each app restart. This sounds like it could lead to some weird session persistance behaviour.
If you don't have a config loader (yet), you can just hard-code the value right after you define the app:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super_secure'
Of course set that key to something sensible. If you want to generate this with Python, use the secrets module rather than os.urandom. However, again, you should passing the key as an actual string, rather than generating it dynamically on each app launch, for the reason mentioned above.

My code shows this error whatever I try, and when I click on the link it shows there's a 404

Whatever I seem to try (using different secret keys, trying to fix small errors) this error shows when I run my code.
I have tried making small changes to the code such as changing the secret key, fixing indentation, etc. However, I do not understand why my code does not work, so I wanted to ask here.
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secretcodehere29403949493'
socketio = SocketIO(app)
#app.route("/template/chat.html/")
def chat():
return render_template("template/login.html")
#app.route(r'/template/login.html/')
def login():
return render_template('login.html')
#socketio.on('message', namespace='/chat')
def chat_message(message):
print("message = ", message)
emit('message', {'data': message['data']}, broadcast=True)
#socketio.on('connect', namespace='/chat')
def test_connect():
emit('my response', {'data': 'Connected', 'count': 0})
if __name__ == '__main__':
socketio.run(app)
Restarting with stat
Debugger is active!
Debugger PIN: 183-355-780
(18512) wsgi starting up on http://127.0.0.1:5000
nothing displays in the link it provides in the error here, and localhost:8080 shows nothing.
Your routes may not be correct. When you call app.route, you're mapping a url to the function.
In your case the urls in your routes are defining: 127.0.0.1:5000/template/chat.html/ and 127.0.0.1:5000/template/login.html/.
Try changing a route to #app.route('/') and then navigating to 127.0.0.1:5000 or localhost:5000
Concerning your last comment (I can't comment on dylanj.nz's post), the render_template function uses the default templates folder, so there is no need to specify it on your code :)
Thus you should remove template/ in this line:
return render_template("template/login.html").
If you want to change the default folder location, add a template_folder instruction in your app = Flask(...).
Example:
app = Flask(__name__, template_folder='application/templates', static_folder='heyanotherdirectory/static')

RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret

I am making Flask app.
I wrote this code:
from flask import Flask, session
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
#app.route('/my-route')
#cache.cached(timeout=50)
def my_route():
id = request.args.get('id')
schema = Schema({
Required('id'): All(Coerce(str))
})
try:
schema({'id': id})
except MultipleInvalid as e:
str(e)
ans=test(session[‘id’])
return ans
if __name__ == '__main__':
app.run(debug=True)
When I run the append access localhost:8000/my-route?id=aDj1948, I get:
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. error.
I rewrote #cache.cached(timeout=50, key_prefix=make_cache_key), but same error happens. I do not think I have to set secret key somewhere in the codes, so I really cannot understand what is wrong.
How should I fix this?
What is wrong in my codes?
It has nothing to do with cache. In order to use sessions you have to set a secret key: http://flask.pocoo.org/docs/1.0/quickstart/#sessions
Add the following (obviously don't use my example and change the secret key) after initialising your app:
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
You can generate secrets on the fly:
import secrets
secret = secrets.token_urlsafe(32)
app.secret_key = secret
I don't think there is anything related to cache as I tried to clear mine and recheck multiple times.
You just have to just simply add
app.secret_key = 'dd hh' #the secret_key can be anything

Categories