SheffDoinWork
SheffDoinWork

Reputation: 783

Flask session variable not allowing assignment

I've been building a web application for the past month, and things have been going surprisingly smoothly for how new I am to all of this. That is, until yesterday, when I did an AJAX overhaul on a page to provide users with live feedback of a server-side process. Now when I boot up the application, I get an error on my first line of code (which has produced no problems up to this point) where I check the session object to see if an operation is active.

I am getting the error:

UnboundLocalError: local variable 'session' referenced before assignment

when I try the code:

if 'active_op' not in session:
    print 'bizbaz'

I would have thought that I was doing something wrong with this code if it hadn't worked seemlessly before. I've reverted my code to what I had before the AJAX update, and I'm still getting this error, even though it worked yesterday with the same code. Any pointers on this would be greatly appreciated. As I said, I'm still kind of new to web application development and sessions, in particular. Apparently my understanding of sessions and flask's use of them is a bit off, because I'm completely stumped as to why this has suddenly stopped working. Let me know if there's anything I can do to clarify my issue; I'm stuck until I get this figured out. Thanks!

EDIT: I had this code which was trying to assign a dictionary to the session variable.

session = {'foo':'bar'}

Upvotes: 3

Views: 3164

Answers (1)

Sergey Bargamon
Sergey Bargamon

Reputation: 132

Make sure you import session before you use it

from flask import session

EDIT

The main problem was that you were assigning a dictionary to the 'session' variable which you should not do.

# Incorrect
session = {'foo':'bar'}

Instead, it should be

session['foo'] = 'bar'

Upvotes: 6

Related Questions