Search code examples
pythonsessioncgi

python: interact with the session in cgi scripts


Can python cgi scripts write and read data to the session? If so how? Is there a high-level API or must I roll my own classes?


Solution

  • There's no "session" on cgi. You must roll your own session handling code if you're using raw cgi.

    Basically, sessions work by creating a unique cookie number and sending it on a response header to the client, and then checking for this cookie on every connection. Store the session data somewhere on the server (memory, database, disk) and use the cookie number as a key to retrieve it on every request made by the client.

    However cgi is not how you develop applications for the web in python. Use wsgi. Use a web framework.

    Here's a quick example using cherrypy. cherrypy.tools.sessions is a cherrypy tool that handles cookie setting/retrieving and association with data automatically:

    import cherrypy
    
    class HelloSessionWorld(object):
        @cherrypy.tools.sessions()
        def index(self):
            if 'data' in cherrypy.session:
                return "You have a cookie! It says: %r" % cherrypy.session['data']
            else:
                return "You don't have a cookie. <a href='getcookie'>Get one</a>."
        index.exposed = True
    
        @cherrypy.tools.sessions()
        def getcookie(self):
            cherrypy.session['data'] = 'Hello World'
            return "Done. Please <a href='..'>return</a> to see it"
        getcookie.exposed = True
    
    application = cherrypy.tree.mount(HelloSessionWorld(), '/')
    
    if __name__ == '__main__':
        cherrypy.quickstart(application)
    

    Note that this code is a wsgi application, in the sense that you can publish it to any wsgi-enabled web server (apache has mod_wsgi). Also, cherrypy has its own wsgi server, so you can just run the code with python and it will start serving on http://localhost:8080/