1
2
3
4
5
6 """
7 Threadsafe Pool class
8 """
9
10 import collections
11 from restkit import sock
12
14 """ abstract class from which all connection
15 pool should inherit.
16 """
17
19 """ method used to return a connection from the pool"""
20 raise NotImplementedError
21
23 """ Put an item back into the pool, when done """
24 raise NotImplementedError
25
27 """ method used to release all connections """
28 raise NotImplementedError
29
30
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
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