Recent comments

You are here

How to make CherryPy sessions work

I have recently started development with the CherryPy framework to create a python based webserver. In pretty much any website with users you want to create sessions and CherryPy offers a great set of commands to manage user sessions. There is quite a bit of documentation provided about sessions and managing them, also some great code examples. However even with the code examples and searching with Google I found it rather difficult to figure out sessions despite my years of developing with PHP. It seemed I was missing something important so I dedicated a day to getting sessions working in CherryPy. I am using CherryPy version 3.8.0

Session configuration according to many documents online is as simple as adding into your code something like this:


import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        return "Hello world!"

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

We can also add to our configuration some other session options such as
'tools.sessions.storage_type': "file",
'tools.sessions.storage_path': "/tmp/sessions",
'tools.sessions.timeout': 60,

But no matter the example my sessions would still re-generate on each page load. I couldn't find my answer on the internet despite all the different ways I worded it on the search engines. So I decided to think back on how we use sessions in PHP. At the start of each page we had to use the session_start() function to keep our sessions alive. So how about the function cherrypy.session.start()

Well now it showed session info when I loaded the page but now it was throwing an error that the session was already started. I was still wrong but on the right path.

After messing around a bit more I found the key was to include at the beginning of each page a simple function cherrypy.session.load()

That was it easy as Py. CherryPy even that one simple function not shown in any example I was able to find fixed my sessions and it can fix yours too!

So my code then became this:


import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        cherrypy.session.load()
        return "Hello world!"

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

I really hope this helps other people struggling with the same issue as me. I don't understand why its not in any examples out there but it is now. If this tutorial helped you with sessions share it on Facebook and Twitter or any other places you think it would help. Link to it from other sites, my website has been around for many years and should remain up for many to come. Let me know if your still having trouble or if this helped you out I would love feedback from others.

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer