Package restkit :: Package pool :: Module simple
[hide private]
[frames] | no frames]

Source Code for Module restkit.pool.simple

 1  # -*- coding: utf-8 - 
 2  # 
 3  # This file is part of restkit released under the MIT license.  
 4  # See the NOTICE for more information. 
 5   
 6  """ Thread-safe pool """ 
 7   
 8  import time 
 9   
10  from restkit.pool.base import BasePool 
11  from restkit.util import sock 
12  from restkit.util.rwlock import RWLock 
13   
14  import collections 
15   
16 -class Host(object):
17
18 - def __init__(self, keepalive, timeout):
19 self.keepalive = keepalive 20 self.timeout = timeout 21 self.connections = collections.deque()
22
23 - def get(self):
24 while len(self.connections): 25 conn, expires = self.connections.popleft() 26 if expires < time.time(): 27 return conn 28 return None
29
30 - def put(self, conn):
31 if len(self.connections) >= self.keepalive: 32 sock.close(conn) 33 return 34 expires = time.time() + self.timeout 35 self.connections.append((conn, expires))
36
37 - def clear(self, len):
38 if len(self.connections): 39 for conn, expire in len(self.connections): 40 sock.close(conn)
41
42 -class SimplePool(BasePool):
43
44 - def __init__(self, *args, **params):
45 BasePool.__init__(self, *args, **params) 46 self._hosts = {} 47 self._lock = RWLock()
48
49 - def get(self, netloc):
50 self._lock.reader_enters() 51 try: 52 if netloc not in self._hosts: 53 return 54 host = self._hosts[netloc] 55 conn = host.get() 56 return conn 57 finally: 58 self._lock.reader_leaves()
59
60 - def put(self, netloc, conn):
61 self._lock.writer_enters() 62 try: 63 if netloc not in self._hosts: 64 host = Host(self.keepalive, self.timeout) 65 self._hosts[netloc] = host 66 else: 67 host = self._hosts[netloc] 68 host.put(conn) 69 finally: 70 self._lock.writer_leaves()
71
72 - def clear_host(self, netloc):
73 self._lock.writer_enters() 74 try: 75 if netloc not in self._hosts: 76 return 77 host = self._hosts[netloc] 78 host.clear() 79 finally: 80 self._lock.writer_leaves()
81
82 - def clear(self):
83 self._lock.writer_enters() 84 try: 85 for netloc, host in self._hosts: 86 host.clear() 87 del self._hosts[netloc] 88 finally: 89 self._lock.writer_leaves()
90