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

Source Code for Module restkit.conn.eventlet_manager

 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   
 8  from restkit.conn.base import Pool, ConnectionManager 
 9  from restkit.conn import http_connection 
10   
11  from eventlet.green import socket 
12  from eventlet.green import ssl 
13  from eventlet import queue 
14  from eventlet import semaphore 
15   
16 -class EventletHttpConnection(http_connection.HttpConnection):
17
18 - def connect(self):
19 self.filters.apply("on_connect", self) 20 21 self.sock = socket.create_connection(self.addr, 22 timeout=self.timeout) 23 if self.is_ssl: 24 self.sock = ssl.GreenSSLSocket(self.sock, **self.kwargs)
25 26 27 28
29 -class EventletPool(Pool):
30
31 - def __init__(self, conn_manager, route, timeout=300, 32 nb_connections=10):
33 self.conn_manager = conn_manager 34 self.route = route 35 self.nb_connections = nb_connections 36 self.timeout = timeout 37 self.connections = queue.PriorityQueue() 38 self.iddle_connections = {} 39 self.active_connections = {}
40
41 - def request(self):
42 self.clean_iddle_connections() 43 try: 44 expires, conn = self.connections.get_nowait() 45 except queue.Empty: 46 conn = EventletHttpConnection( 47 self.conn_manager, 48 self.route[0], 49 self.route[1], 50 timeout=self.timeout, 51 filters=self.route[2], 52 **self.route[3]) 53 return conn
54
55 - def release(self, conn, duration=300):
56 if self.connections.qsize() >= self.nb_connecions: 57 conn.close() 58 return 59 expires = time.time() + duration 60 self.connections.put_nowait((expires, conn))
61
62 - def clean_iddle_connections(self):
63 while True: 64 try: 65 expires, conn = self.connections.get_nowait() 66 except queue.Empty: 67 break 68 if time.time() > expires: 69 conn.close() 70 else: 71 self.connections.put((expires, conn)) 72 break
73
74 - def shutdown(self):
75 while True: 76 try: 77 expires, conn = self.connections.get_nowait() 78 conn.close() 79 except queue.Empty: 80 break
81 82
83 -class EventletConnectionManager(ConnectionManager):
84 85 POOL_CLASS = EventletPool 86
87 - def init_lock(self):
88 return semaphore.Semaphore(1)
89