[Twisted-Python] returning a deferred in getStateToCopyFor.

Glyph glyph at twistedmatrix.com
Sat Mar 31 14:53:50 EDT 2012

On Mar 31, 2012, at 5:59 AM, Flint wrote:

> Hi, all.
> using PB i wanted to implement some access control check on my copyable objects.
> so i placed that in getStateToCopyFor, all is ok except when i need to perfom some asynchronous call in that method.
> ex: (i use twisted 10.1.0)
> ...
> def getStateToCopyFor(self, user):
>   state = self.getStateToCopy()
>   d = user.has_perm()  # this do an asynchronous call
>   def got_perm(allowed, state):
>     if not allowed:
>       state['secret'] = ''
>       return state 
>   d.addCallback(got_perm, state)
>   return d
> ...  
> here user.has_perm performe a database access so it returns a deferred, but when i return that deferred, i got an error saying that 'state' is not a dict (which is quit normal cause it's a deferred).
> it seems pb do not handle this case, i know i can put my control logic directly in the view method (where returning a deferred is handled) but this will lead to a lot of code duplication, and i really thought that getStateToCopyFor is made for that purpouse.
> so i wanted to ask what's the best way to achieve that ?

This is not the intended use of getStateToCopyFor.  It is called when the object is already being sent to the other side, so it is implicitly synchronous; it's saying "what is the local (i.e. synchronously accessible) state of this object, right now".

If the user shouldn't have access to the object, don't send it to them in the first place :).


More information about the Twisted-Python mailing list