'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?
Solution 1:[1]
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]/'
Solution 2:[2]
You can generate secrets on the fly:
import secrets
secret = secrets.token_urlsafe(32)
app.secret_key = secret
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Selcuk |
Solution 2 | Chiffa |
Solution 3 | Chucky.kurra |