How to store cherrypy.session() in a variable?

1.3k Views Asked by At

First, I store an email in my session:

@cherrypy.expose
def setter(self):
    email = "[email protected]"
    cherrypy.session["email"] = email
    return "Variable passed to session" // This works fine! 

  

Second, I return the session data:

@cherrypy.expose
def getter(self):
    return cherrypy.session("email") // This works fine too! 

But now, I would like to store this data in a variable and return it:

@cherrypy.expose
def getter(self):
    variable = cherrypy.session("email")
    return variable

When doing this, I get a 500 Internal: KeyError 'variable'

1

There are 1 best solutions below

0
On BEST ANSWER

Don't forget to turn sessions on in the config. It's disabled by default. Also, you use cherrypy.session as a dictionary, it's not a function you call.

Take this example code:

# rimoldi.py

import cherrypy

class TestApp:

    @cherrypy.expose
    def setter(self):
        email = "[email protected]"
        cherrypy.session["email"] = email
        return 'Variable stored in session object. Now check out the <a href="/getter">getter function</a>'

    @cherrypy.expose
    def getter(self):
        return "The email you set earlier, was " + cherrypy.session.get("email")

if __name__ == '__main__':
    cherrypy.quickstart(TestApp(), "/", {
        "/": {
            "tools.sessions.on": True,
            }
        })

You run the above example with:

python rimoldi.py

CherryPy says:

[09/Jan/2017:16:34:32] ENGINE Serving on http://127.0.0.1:8080
[09/Jan/2017:16:34:32] ENGINE Bus STARTED

Now point your browser at http://127.0.0.1:8080/setter, and you'll see:

Variable stored in session object. Now check out the getter function

Click the 'getter' link. The browser shows:

The email you set earlier, was [email protected]

Voila! This is how you use sessions in CherryPy. I hope this example helps you.