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

Source Code for Module restkit.pool

 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  """ 
 7  Threadsafe Pool class  
 8  """ 
 9   
10  import collections 
11  from restkit import sock 
12   
13 -class PoolInterface(object):
14 """ abstract class from which all connection 15 pool should inherit. 16 """ 17
18 - def get(self):
19 """ method used to return a connection from the pool""" 20 raise NotImplementedError
21
22 - def put(self):
23 """ Put an item back into the pool, when done """ 24 raise NotImplementedError
25
26 - def clear(self):
27 """ method used to release all connections """ 28 raise NotImplementedError
29 30
31 -class ConnectionPool(PoolInterface):
32 - def __init__(self, max_connections=4):
33 """ Initialize ConnectionPool 34 :attr max_connections: int, the number of maximum connectioons 35 per _host_port 36 """ 37 self.max_connections = max_connections 38 self.hosts = {}
39
40 - def get(self, address):
41 connections = self.hosts.get(address) 42 if connections: 43 socket = connections.popleft() 44 self.hosts[address] = connections 45 return socket 46 return None
47
48 - def put(self, address, socket):
49 connections = self.hosts.get(address) 50 if not connections: 51 connections = collections.deque() 52 53 # do we have already enough connections opened ? 54 if len(connections) > self.max_connections: 55 sock.close(socket) 56 return 57 58 connections.append(socket) 59 self.hosts[address] = connections
60
61 - def clear(self, address):
62 connections = self.hosts.get(address) 63 while True: 64 if not connections: break 65 socket = connections.popleft() 66 sock.close(socket) 67 socket.close()
68