Question

Can someone please tell me the difference between

urls = (
    "/count", "count",
    "/reset", "reset")
app = web.application(urls, locals())
store = web.session.DiskStore('sessions')
session = web.session.Session(app, store, initializer={'count': 0})
class count:
    def GET(self):
        session.count += 1
        return str(session.count)
class reset:
    def GET(self):
        session.kill()
        return ""
if __name__ == "__main__":
    app.run()

and

urls = (
    "/count", "count",
    "/reset", "reset")
app = web.application(urls, locals())
class count:
    counting = 0
    def GET(self):
        count.counting += 1
        return str(count.counting)
class reset:
    def GET(self):
        count.counting = 0
        return ""
if __name__ == "__main__":
    app.run()

Both their output is exactly the same as far as I can tell. If there is no difference then what is the advantage of using Session objects over variables like this ?

I am pretty new to Python and going through Zed Shaw's Learn Python the Hard Way. I was on exercise 52 where he introduces sessions when this question popped into my head.

Was it helpful?

Solution

In the second instance, all browsers that connect to your application share a single counter. In the first instance, each browser counts according to its own session.

And, as kubked pointed out, the counter is persisted on disk in the first instance.

Reference: http://webpy.org/cookbook/sessions

OTHER TIPS

As far as i see in https://gitorious.org/lpthw-web/lpthw-web/source/b1ab4df58746c5d4e3dfb41e502a8192caec3ef1:web/session.py DiskStore session will keep session in file system. If server crashes you can run it once again and opened session will be still stored. With keeping data in variable, which means it will be stored in RAM, server crash cause losing it.

Of course keeping user data in session will be also better when you decide to use threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top