[Twisted-web] Nevow: How to use sessions?

Donovan Preston dp at ulaluma.com
Tue Dec 14 09:01:06 MST 2004


On Dec 14, 2004, at 6:24 AM, Mohamed Lrhazi wrote:

> Can someone give a helloworld example of how to store and retrieve 
> objects specific to a session ? maybe a counter example. The objects 
> would need to be destroyed automatically when the session expires.

The object returned from ISession(ctx) is yours to do with as you 
please. If your application is the only application which will be 
running on the server, then you can get and set attributes on it to 
store whatever information you like:

ISession(ctx).foo = 1

then later...

getattr(ISession(ctx), 'foo', None)

Which is kind of a pain...

However, if your application might be mixed and matched with other 
people's applications (not super likely at the moment) you may want to 
set a component on the session using an interface unique to your 
application:

> In the examples I see things like:
>
> def setupSession(self, ctx):
>        #need to place the user, usermanager in the session
>        inevow.ISession(ctx).setComponent(ICurrentUser, self.user)
>        inevow.ISession(ctx).setComponent(IUserManager, 
> self.userManager)
> and
>
> self.userManager = request.session.getComponent(IUserManager)
>
> Can I just do that to store any object? do I have to create an 
> interface for it?

If you want to do that, yes, you can do that. Just subclass 
compy.Interface and use any object as the component value. Instead of 
using request.session.getComponent, I would use the spelling:

IUserManager(ISession(ctx))

This will fail if the session has not had an IUserManager component set 
on it yet, however. You can pass a default value to the IUserManager 
adaption, or you can register an IUserManager adapter for GuardSession 
so that the adapter will automatically be constructed and set as a 
component on the session if it has not already. For example:

compy.registerAdapter(UserManager, GuardSession, IUserManager)

In this way, when you say IUserManager(ISession(ctx)) without having 
previously called setComponent on the session with the IUserManager 
interface, your UserManager adapter will be constructed and set on the 
session for you automatically. Future calls to 
IUserManager(ISession(ctx)) will return the same instance.

Hope this helps,
dp




More information about the Twisted-web mailing list