Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

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?

like image 642
user10102827 Avatar asked Jul 20 '18 06:07

user10102827


2 Answers

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]/'
like image 71
Selcuk Avatar answered Nov 11 '22 03:11

Selcuk


You can generate secrets on the fly:

import secrets

secret = secrets.token_urlsafe(32)

app.secret_key = secret
like image 33
Chiffa Avatar answered Nov 11 '22 05:11

Chiffa