This repository has been archived by the owner on Oct 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.py
54 lines (46 loc) · 1.46 KB
/
http.py
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
import httplib
import urllib
import socket
import time
class HttpClient:
"""small wrapper around httplib"""
def __init__(self, host, port):
self.conn = httplib.HTTPConnection(host, port)
self.connected = False
def _ensure_connection(self):
if self.connected: return
# loop to sleep while server isn't listening
while True:
try:
self.conn.connect()
self.connected = True
return
except socket.error, e:
if e.errno == 111:
time.sleep(1)
continue
raise
def request(self, method, url, body='', headers={}):
self._ensure_connection()
self.conn.request(method, url, body, headers)
r = self.conn.getresponse()
body = r.read()
return (r, body)
def post(self, path, body, **kw):
if len(kw):
url = '%s?%s' % (path, urllib.urlencode(kw))
else:
url = path
return self.request('POST', url, body)
def get(self, path, **kw):
if len(kw):
url = '%s?%s' % (path, urllib.urlencode(kw))
else:
url = path
return self.request('GET', url)
if __name__ == '__main__':
c = HttpClient('localhost', 13082)
r = c.get('/test', this='that', one=1, space='this has spaces')
r.read()
r = c.get('/test', this='that', one=1, space='this has spaces')
r.read()