forked from jacksonj/CouchProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCouchProxyRequest.py
More file actions
66 lines (60 loc) · 2.53 KB
/
Copy pathCouchProxyRequest.py
File metadata and controls
66 lines (60 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import socket
import httplib2
class CouchProxyRequest:
"""
Handles onwards requests to the remote couch / front end. No
processing of data is performed - intended to be used as the
outward bound leg of a proxy
"""
def __init__(self, host, cert_file = None, key_file = None):
"""
Configures the request object, loading the required
URL opener depending on whether key / cert is provided
"""
self.host = host
if cert_file and key_file:
self.conn = self._getSSLURLOpener(cert_file, key_file)
else:
self.conn = self._getURLOpener()
def makeRequest(self, resource, verb='GET', headers={}, body=""):
"""
Make a request to the remote host
"""
# Form complete URI
uri = self.host + resource
# Now attempt to send the request
try:
response, result = self.conn.request(uri, method = verb,
body = body, headers = headers,
connection_type = self.con_type)
if response.status == 408: # timeout can indicate a socket error
response, result = self.conn.request(uri, method = verb,
body = body, headers = headers,
connection_type = self.con_type)
except (socket.error, AttributeError):
[conn.close() for conn in self.conn.connections.values()]
# ... try again... if this fails propagate error to client
try:
response, result = self.conn.request(uri, method = verb,
body = body, headers = headers,
connection_type = self.con_type)
except AttributeError:
# socket/httplib really screwed up - nuclear option
self.conn.connections = {}
raise socket.error, 'Error contacting: %s' % self.host
# Pass back the response
return result, response
def _getURLOpener(self):
"""
method getting an HTTPConnection
"""
self.con_type = None
return httplib2.Http(".cache", 30)
def _getSSLURLOpener(self, cert, key):
"""
method getting a secure (HTTPS) connection
"""
http = httplib2.Http(".cache", 30)
http.add_certificate(key=key, cert=cert, domain='')
self.con_type = httplib2.HTTPSConnectionWithTimeout
return http