On Jun 13, 8:38 pm, "Patrick Quinn" <[EMAIL PROTECTED]> wrote:
> I'd like to maintain a resource (python object) between multiple
> requests and multiple users. In this case, I'd like my app to
> maintain a Jabber connection which is established when it's needed and
> kept as long as possible. This way the app can IM users as needed
> without having to go through the very expensive process of negotiating
> a connection with a Jabber server every time a message needs to be
> sent.
>
> Does anyone have any ideas of how this might be achieved within Django?
Here is (part of) a class that does something similar. The Imap
instances are stored in a django session, the imap instance variable
is saved in a module level dictionary, and __getstate__ and
__setstate__ methods keep the imap instance variable out of the
pickled representation and try to restore the active imap handles when
unpickling. When unpickling an object that has no corresponding
Imap.imap handle in the module dictionary a new server connection is
created.
_imap_handles = {}
try:
from mod_python import apache
_log_notice = lambda a: apache.log_error(a, apache.APLOG_NOTICE)
_log_error = lambda a: apache.log_error(a)
except ImportError:
import sys
_log_error = _log_notice = lambda a: sys.stderr.write("%s\n" % a)
from imaplib import IMAP4_SSL as IMAP4
class Imap(object):
def __init__(self, host=None, user=None, password=None, key=None):
self._host, self.user, self._password = host, user, password
self.key = key
self.imap = None
if self.connect():
_imap_handles[key] = self.imap
def close(self):
self.imap.close()
try:
del _imap_handles[self.key]
except:
pass
def connect(self):
_log_notice("imap login %s to %s" % (self.user, self._host))
try:
self.imap = imap = IMAP4(self._host)
if self.user and self._password:
imap.login(self.user, self._password)
return imap
except Exception, e:
_log_error("login failed for %s: %s" % (self.user,
str(e)))
def __getstate__(self):
return dict([(k,v) for k,v in self.__dict__.items() if not
k=='imap'])
def __setstate__(self, obj):
self.__dict__.update(obj)
key = self.key
self.imap = _imap_handles.get(key)
if self.imap is None:
if (self.connect()):
_imap_handles[key] = self.imap
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---