Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask with a webserver breaks all sessions?

For example, this code:

from flask import session

@app.route('/is_logged_in/')
def is_logged_in():
  return 'user' in session

It runs fine for me when running Flask's development server, but it throws a 500 error with any webserver setup (FastCGI, uWSGI, etc.) on any server (Apache, nginx, Lighttpd).

Anybody know why?


My actual code is on GitHub, if it matters.

It works flawlessly when running with Flask's internal server, but I can't get any session variables to work with a production webserver: https://github.com/Blender3D/Webminal/blob/master/server.py

like image 337
Blender Avatar asked Dec 06 '22 16:12

Blender


2 Answers

I finally tried Tornado, thinking it would help with my problems (it's written in Python, after all).

Lo and behold, a readable traceback:

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

Looks like I just forgot to add a secret key to sign sessions with:

app.secret_key = 'why would I tell you my secret key?'
like image 125
Blender Avatar answered Dec 09 '22 14:12

Blender


Your return value must be one of several types: a basestring (string or unicode), a tuple (representing arguments passed to the constructor of a Response object), a Response object itself, or -- failing those -- a WSGI-callable function.

You are returning a bool. Flask is assuming that since it's not a basestring, tuple or Response object, it must be a WSGI-callable. Subsequently, when processing the response it attempts to call() your bool return value which results in an exception. Flask catches the resulting TypeError. When Flask is in debug mode, it'll pass this back up to Werkzeug's simple webserver, which will invoke the built-in debugger. When Flask is in production mode, however, it'll merely bubble up an internal server error -- e.g., code 500 -- with no further information.

So, to fix your problem, make sure you do this instead:

return str('user' in session)

like image 29
twooster Avatar answered Dec 09 '22 15:12

twooster