Using sessions in web.py

tutorial backend tutorial webdev webpy

Intro

Sessions in web.py are like server-side cookies. Cookies are objects used to store simple information for either identification purposes or to keep track of user’s preference. (If you already knew that, give yourself a cookie -> yep, that brown backed confection). Sessions are used to identify different users on the website, they make use of client-side cookies and IP address for identification, among other things.

When you try out other tutorials out there, you might find yourself stuck at some parts, getting random errors that makes little sense to you. I have been through that process and I am here to share how it is actually done.

For the tutorial, I will be making a simple counter app that makes use of sessions to track the number of times a page is visited. There is an explained version for those that are not too used to webpy framework and could use some help with the code.

app.py (short and sweet version):

import web

urls = [
    "/", "Index",
    "k", "Kill"
]
app = web.application(urls, globals())

if not web.config.get("session"):
    session = web.session.Session(app,
        web.session.DiskStore("./sessions"),
        initializer={"count":0}
    )
    web.config.session = session
else:
    session = web.config.session

class Index:
    def GET(self):
        session["count"] += 1
        return session["count"]

class Kill:
    def GET(self):
        return web.seeother("/")

if __name__ == "__main__":
    app.run()

app.py (explained):

Readings