Package restkit :: Package conn :: Module threaded
[hide private]
[frames] | no frames]

Source Code for Module restkit.conn.threaded

 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  import time 
 7  import collections 
 8  import threading 
 9   
10  from restkit.conn.base import Pool, ConnectionManager 
11  from restkit.conn.http_connection import HttpConnection 
12  from restkit.util import sock 
13   
14 -class TPool(Pool):
15
16 - def __init__(self, conn_manager, route, timeout=300, 17 nb_connections=10):
18 self.conn_manager = conn_manager 19 self.route = route 20 self.nb_connections = nb_connections 21 self.timeout = timeout 22 self.connections = collections.deque() 23 self.active_connections = {} 24 self._lock = threading.Lock()
25
26 - def request(self):
27 self.clean_iddle_connections() 28 29 try: 30 conn, expires = self.connections.popleft() 31 except IndexError: 32 conn = HttpConnection( 33 self.conn_manager, 34 self.route[0], 35 self.route[1], 36 timeout=self.timeout, 37 filters=self.route[2], 38 **self.route[3]) 39 self.active_connections[conn] = (conn, time.time()) 40 return conn
41
42 - def release(self, conn, duration=300):
43 if conn not in self.active_connections or \ 44 len(self.connections) > self.nb_connections: 45 conn.close() 46 return 47 expires = time.time() + duration 48 self.connections.append((conn, expires)) 49 del self.active_connections[conn]
50
51 - def clean_iddle_connections(self):
52 self._lock.acquire() 53 try: 54 for conn, duration in self.connections: 55 if time.time() > duration: 56 self.connections.remove((conn, duration)) 57 else: 58 # no need to continue since we are ordered. 59 break 60 finally: 61 self._lock.release()
62
63 - def shutdown(self):
64 while self.connections: 65 conn, expires = self.connections.pop() 66 sock.close(conn)
67
68 -class TConnectionManager(ConnectionManager):
69 70 POOL_CLASS = TPool
71