[Twisted-web] Get access to Avatar from Resource object?

Phil Mayers p.mayers at imperial.ac.uk
Mon Mar 5 12:45:13 EST 2012

On 05/03/12 15:19, Jacek Furmankiewicz wrote:
> Hm, I would prefer to avoid that.
> In my case, the cost of creating a new Resource is high (since it needs
> to parse all the URLs it can dispatch to for all the REST services),
> therefore I would prefer to cache a single ReadOnlyResource vs
> AdminResource (as an example)

If you search the archives, you will find discussions on this.

The general conclusion was: Resource objects should be lightweight and 
fast. If you've got expensive stuff, pre-computer / cache / share / 
whatever, and make your Resource objects talk to the cache.

> and just serve one or the other.

So? Do that:

avatars = {}

class MyRealm:
   def requestAvatar(...):

     if is_admin(avatarId):
       if not 'admin' in avatars:
          avatars['admin'] = MyAdmin()
       return avatars['admin'], ...

Of course, you'll be re-using the same avatar for all admins, and won't 
be able to distinguish them, or access their usernames.

Alternatively you might have a lightweight resource that just does 
simple authorization / logging, and passes render calls through to the 
heavyweight resource:

class MyAdmin():
   def render(...):
     request.username = self.username
     return CachedHeavyAdmin.render(request, ...)

class MyRealm():
   def requestAvatar(...):
     if is_admin(avatarId):
       r = MyAdmin()
       r.username = avatarId
       return r

More information about the Twisted-web mailing list