Skip to content
This repository was archived by the owner on Apr 15, 2024. It is now read-only.

Commit 7f705d5

Browse files
committed
start pulling all of this mess together
1 parent 09567e4 commit 7f705d5

3 files changed

Lines changed: 89 additions & 85 deletions

File tree

consul/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from consul.core import connect

consul/core.py

Lines changed: 79 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,19 @@
11
import collections
2+
import urllib2
23
import urllib
34

4-
import requests
5-
65

76
__version__ = '0.1'
87

98

10-
Response = collections.namedtuple('Response', ['code', 'headers', 'body'])
11-
12-
13-
class HTTPClient(object):
14-
def __init__(self, host, port):
15-
self.host = host
16-
self.port = port
17-
self.base_uri = 'http://%s:%s' % (self.host, self.port)
18-
19-
def response(self, response):
20-
return Response(response.status_code, response.headers, response.text)
21-
22-
def uri(self, paths, params=None):
23-
uri = self.base_uri + '/'.join(paths)
24-
if not params:
25-
return uri
26-
return '%s?%s' % (uri, urllib.urlencode(params))
27-
28-
def get(self, callback, uri, params=None, data=None):
29-
print uri
30-
return callback(self.response(requests.get(uri)))
31-
32-
def put(self, callback, uri, params=None, data=None):
33-
print uri
34-
return callback(self.response(requests.put(uri, data=data)))
9+
__all__ = ['__version__', 'connect']
3510

3611

37-
def prepare_params(values):
38-
ret = {}
39-
if values.get('index'):
40-
ret['index'] = values['index']
41-
if values.get('recurse'):
42-
ret['recurse'] = '1'
43-
return ret
44-
45-
46-
def execute(http, method, path, name, args, local):
47-
if method == 'put':
48-
data = local[args[-1]]
49-
args = args[:-1]
50-
else:
51-
data = None
52-
53-
uri = http.uri(
54-
[path, name] + [local[x] for x in args],
55-
params=prepare_params(local))
56-
57-
return getattr(http, method)(lambda x: x, uri, data)
58-
59-
60-
def command(method, *args, **kwargs):
12+
def command(last, method, *args, **kwargs):
6113
def make(http, path, name):
14+
if last is not None:
15+
path = path + '/' + last
16+
6217
# generate signature
6318
params = kwargs.pop('params', None)
6419
code = "def " + name + "("
@@ -72,7 +27,7 @@ def make(http, path, name):
7227

7328
# body
7429
code += """
75-
return execute(http, method, path, name, args, locals())
30+
return execute(http, method, path, args, locals())
7631
"""
7732

7833
# generate code
@@ -91,19 +46,82 @@ def make(http, path, name):
9146
commands = {
9247
'v1': {
9348
'kv': {
94-
'get': command('get', 'key', params=['index', 'recurse']),
95-
'put': command('put', 'key', 'value'),
49+
'get': command(None, 'get', 'key', params=['index', 'recurse']),
50+
'put': command(None, 'put', 'key', 'value'),
9651
},
9752
'agent': {
98-
'self': command('get'),
53+
'self': command('self', 'get'),
9954
'service': {
100-
'register': command('get', 'name'),
55+
'register': command('register', 'get', 'name'),
10156
},
10257
},
10358
'health': lambda *a: None,
10459
}, }
10560

10661

62+
Response = collections.namedtuple('Response', ['code', 'headers', 'body'])
63+
64+
65+
class HTTPClient(object):
66+
def __init__(self, host, port):
67+
self.host = host
68+
self.port = port
69+
self.base_uri = 'http://%s:%s' % (self.host, self.port)
70+
71+
def response(self, fh):
72+
ret = Response(fh.getcode(), fh.info().dict, fh.read())
73+
fh.close()
74+
return ret
75+
76+
def uri(self, paths, params=None):
77+
uri = self.base_uri + '/'.join(paths)
78+
if not params:
79+
return uri
80+
return '%s?%s' % (uri, urllib.urlencode(params))
81+
82+
def get(self, callback, uri, params=None, data=None):
83+
print
84+
print uri
85+
response = self.response(urllib.urlopen(uri))
86+
return callback(response)
87+
88+
def put(self, callback, uri, params=None, data=None):
89+
print
90+
print uri
91+
opener = urllib2.build_opener(urllib2.HTTPHandler)
92+
request = urllib2.Request(uri, data=data)
93+
# request.add_header('Content-Type', 'your/contenttype')
94+
request.get_method = lambda: 'PUT'
95+
try:
96+
response = opener.open(request)
97+
except urllib2.HTTPError, response:
98+
pass
99+
response = self.response(response)
100+
return callback(response)
101+
102+
103+
def prepare_params(values):
104+
ret = {}
105+
if values.get('index'):
106+
ret['index'] = values['index']
107+
if values.get('recurse'):
108+
ret['recurse'] = '1'
109+
return ret
110+
111+
112+
def execute(http, method, path, args, local):
113+
if method == 'put':
114+
data = local[args[-1]]
115+
args = args[:-1]
116+
else:
117+
data = None
118+
119+
uri = http.uri(
120+
[path] + [local[x] for x in args], params=prepare_params(local))
121+
122+
return getattr(http, method)(lambda x: x, uri, data)
123+
124+
107125
class EndPoint(object):
108126
def __init__(self, path):
109127
self.path = path
@@ -112,31 +130,16 @@ def __repr__(self):
112130
return 'EndPoint("%s")' % self.path
113131

114132

115-
def f(http, commands, path):
133+
def build(http, commands, path):
116134
endpoint = EndPoint(path)
117135
for key, command in commands.iteritems():
118136
if isinstance(command, dict):
119-
setattr(endpoint, key, f(http, command, path+'/'+key))
137+
setattr(endpoint, key, build(http, command, path+'/'+key))
120138
else:
121139
setattr(endpoint, key, command(http, path, key))
122140
return endpoint
123141

124142

125-
def main():
126-
127-
import inspect
128-
129-
http = HTTPClient('localhost', 8500)
130-
131-
api = f(http, commands['v1'], '/v1')
132-
133-
print api.agent.service.register
134-
print inspect.getargspec(api.agent.service.register)
135-
print api.agent.service.register('foo')
136-
137-
return
138-
print api.kv.put('foo', 'bar')
139-
print api.kv.get('foo')
140-
141-
142-
main()
143+
def connect(host='127.0.0.1', port=8500):
144+
http = HTTPClient(host, port)
145+
return build(http, commands['v1'], '/v1')

tests/test_core.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import pytest
1010
import py
1111

12+
import consul
13+
1214

1315
def get_free_ports(num, host=None):
1416
if not host:
@@ -26,7 +28,7 @@ def get_free_ports(num, host=None):
2628

2729

2830
@pytest.yield_fixture(scope="module")
29-
def consul():
31+
def consul_port():
3032
ports = dict(zip(
3133
['http', 'rpc', 'serf_lan', 'serf_wan', 'server', 'dns'],
3234
get_free_ports(5) + [-1]))
@@ -44,18 +46,16 @@ def consul():
4446
p = subprocess.Popen(
4547
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
4648

47-
time.sleep(0.5)
49+
time.sleep(2)
4850
yield ports['http']
4951
p.terminate()
5052

5153

52-
def test_core(consul):
54+
def test_core(consul_port):
5355
print
5456
print
55-
print consul
56-
57+
c = consul.connect(port=consul_port)
5758

58-
def test_foo(consul):
59-
print
60-
print
61-
print consul
59+
print c.kv.get('foo')
60+
print c.kv.put('foo', 'bar')
61+
print c.kv.get('foo')

0 commit comments

Comments
 (0)