9
votes

Am running with Python 2.7, Apache + mod_wsgi on CentOS 6.3

Things work fine when I am on localhost. However, when I run the code on a vm in Azure, I do not see the session information being persisted across pages.

Basically in my views, I have something like:

@frontend.route('/')
def index():
   session['foo'] = 'bar'
   print session['foo']

   return redirect(url_for("frontend.page2"))

@frontend.route('page2')
def page2():
   print session

The print output is:

bar
<SecureCookieSession {}>

My wsgi configuration for apache is:

WSGISocketPrefix /var/run/wsgi

<VirtualHost *:80>
    ServerName example.com
    ServerAlias example.com

    WSGIDaemonProcess myproj threads=5 processes=5
    WSGIScriptAlias / /home/mydir/myproj/apache/myproj.wsgi

    <Directory /home/mydir/myproj>
        WSGIScriptReloading On
        WSGIProcessGroup myproj
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

I have the secret_key set:

app.secret_key = os.urandom(24)

I have tried with both setting SERVER_NAME but it doesn't help:

app.config['SERVER_NAME'] = 'example.com' 

Any ideas on how I can debug this more?

Thanks!

1
Do you have a secret key? It's required for sessions: app.secret_key = 'something long and random'Blender
Yes I have secret key. Thx.El Diablo
Where do you store your sessions?cababunga
@cababunga: I was using Flask's default storage. The problem is fixed, it was the issue mata pointed out.El Diablo

1 Answers

25
votes

Don't use app.secret_key = os.urandom(24)!

You're supposed to enter a static value here, not read from os.urandom each time. You've probably misunderstood the example in the docs, it shows you how you can read random data from os.urandom, but it also clearly states:

Just take that thing and copy/paste it into your code and you’re done

If you read it at runtime, then each of your worker processes will have a different secret key! That means if a request is handled by a different worker, the session will break because the cookie is signed with the wrong secret key.