From 5c0332721adb54e03c1e43175bb10bf9e8da0d97 Mon Sep 17 00:00:00 2001 From: Honza Kral Date: Sat, 4 May 2013 20:00:39 +0200 Subject: [PATCH] ElasticSearch client class --- elasticsearch/client.py | 26 ++++++++++++++++++++++++++ test_elasticsearch/test_client.py | 19 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 elasticsearch/client.py create mode 100644 test_elasticsearch/test_client.py diff --git a/elasticsearch/client.py b/elasticsearch/client.py new file mode 100644 index 00000000..0bc0d28b --- /dev/null +++ b/elasticsearch/client.py @@ -0,0 +1,26 @@ +from .transport import Transport + +def _normalize_hosts(hosts): + # if hosts are empty, just defer to defaults down the line + if hosts is None: + return [{}] + + out = [] + # normalize hosts to dicts + for i, host in enumerate(hosts): + if isinstance(host, (type(''), type(u''))): + h = {"host": host} + if ':' in host: + # TODO: detect auth urls + host, port = host.rsplit(':', 1) + if port.isdigit(): + port = int(port) + h = {"host": host, "port": port} + out.append(h) + else: + out.append(host) + return out + +class ElasticSearch(object): + def __init__(self, hosts=None, **kwargs): + self.transport = Transport(_normalize_hosts(hosts), **kwargs) diff --git a/test_elasticsearch/test_client.py b/test_elasticsearch/test_client.py new file mode 100644 index 00000000..cabb95d3 --- /dev/null +++ b/test_elasticsearch/test_client.py @@ -0,0 +1,19 @@ +from unittest import TestCase + +from elasticsearch.client import _normalize_hosts + +class TestNormalizeHosts(TestCase): + def test_none_uses_defaults(self): + self.assertEquals([{}], _normalize_hosts(None)) + + def test_strings_are_used_as_hostnames(self): + self.assertEquals([{"host": "elasticsearch.org"}], _normalize_hosts(["elasticsearch.org"])) + + def test_strings_are_parsed_for_port(self): + self.assertEquals( + [{"host": "elasticsearch.org", "port": 42}, {"host": "user:secret@elasticsearch.com"}], + _normalize_hosts(["elasticsearch.org:42", u"user:secret@elasticsearch.com"]) + ) + + def test_dicts_are_left_unchanged(self): + self.assertEquals([{"host": "local", "extra": 123}], _normalize_hosts([{"host": "local", "extra": 123}]))