Carsten Reimer wrote: > Hi, > > Karen Tracey schrieb: > >> On Wed, Sep 30, 2009 at 1:49 PM, Gabriel Rossetti >> <gabriel.rosse...@arimaz.com <mailto:gabriel.rosse...@arimaz.com>> wrote: >> >> > Why can't it be pickled? >> >> Because it has a socket open >> >> > Clearly, since every request is independent, >> > if it really can't be pickled there is no way of passing it from one >> > to the next. Could you store the necessary values to recreate the >> > object? >> > >> >> That is what I currently doing, but the object creation is expensive >> which is why I was looking for another way. So I can't have some sort >> of global dict that would store my objects and the key could be stored >> in the session? >> > > > does the socket really need to be kept open? If it is the only item that > prevents pickling the object consider using the __setstate__ and > __getstate__ methods (s. > http://docs.python.org/library/pickle.html#object.__getstate__ and > http://docs.python.org/library/pickle.html#object.__setstate__ for details). > > For example delete the socket from the object's __dict__ in the > __getstate__ method (called before the object is pickled) and place the > parameters for socket recreation in the object's __dict__ so that they > will get pickled. Return the object's __dict__ from this method. > In __setstate__ (takes the unpickled __dict__ as parameter) get those > parameters for the socket from the unpickled object's __dict__, recreate > the socket and delete the parameters. > > Or is the socket creation the expensive action of this object. Then > please forget what I have writte because it will not help you. > > Otherwise here are examples of possible __getstate__/__setstate__ > methods for your case: > > def create_socket(self, socket_parameters): > """Creates the socket with the given parameters""" > > def __getstate__(self): > """Called when the object is pickled""" > self.socket_parameters = parameters_for_recreation > del self.socket > return self.__dict__ > > def __setstate__(self, newstate): > """Called when the object is unpickled""" > self.__dict__ = newstate > self.socket = self.create_socket(self.socket_parameters) > del self.socket_parameters > > > Hth > > with best regards > > Carsten > > > Hello Carston,
Thank you for your idea, unfortunately the socket creation is expensive because it also logs on to a server (thus there is a handshake, auth, etc). But I didn't know about __getstate__/__setstate__, thank you very much, it could be useful somewhere else. Best regards, Gabriel --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---