Skip to content

Commit

Permalink
Merge a711c4d into e1187ff
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoErcolanelli committed Oct 25, 2016
2 parents e1187ff + a711c4d commit 9e55330
Show file tree
Hide file tree
Showing 12 changed files with 193 additions and 294 deletions.
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ before_script:
- unzip -q google_appengine_1.9.27.zip
install:
- pip install --upgrade pip
- if [[ $TOXENV == 'py32' ]]; then pip install -I 'virtualenv<14.0'; fi
- pip install tox
script:
- tox
python: 3.5
env:
matrix:
- TOXENV=py26
- TOXENV=py27
- TOXENV=py32
- TOXENV=py33
Expand Down
13 changes: 9 additions & 4 deletions algoliasearch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,21 @@
THE SOFTWARE.
"""

from .client import Client
from .index import Index
from .version import VERSION
from .helpers import AlgoliaException

# Everything underneath is kept for retro-compatibility.
from . import client
from . import index
from . import helpers
from . import version


# Compatibility with old import
class algoliasearch(object):
VERSION = version.VERSION

Client = client.Client
Index = index.Index
AlgoliaException = helpers.AlgoliaException
Client = Client
Index = Index
AlgoliaException = AlgoliaException
44 changes: 23 additions & 21 deletions algoliasearch/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,22 @@
THE SOFTWARE.
"""

import hmac
import hashlib
import base64
import hashlib
import hmac
import random
import sys

from .helpers import deprecated, safe, urlify
from .index import Index
from .transport import Transport
from .version import VERSION

try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode

from .version import VERSION
from .index import Index

from .transport import Transport
from .helpers import deprecated
from .helpers import safe
from .helpers import urlify


MAX_API_KEY_LENGTH = 500

Expand All @@ -58,7 +55,8 @@ def __init__(self, app_id, api_key, hosts=None, _transport=None):
@param app_id the application ID you have in your admin interface
@param api_key a valid API key for the service
@param hosts_array the list of hosts that you have received for the service
@param hosts_array the list of hosts that you have received for the
service
"""
self._transport = Transport() if _transport is None else _transport

Expand Down Expand Up @@ -134,9 +132,11 @@ def enable_rate_limit_forward(self, end_user_ip, rate_limit_api_key):
"""
Allow to use IP rate limit when you have a proxy between end-user and
Algolia. This option will set the X-Forwarded-For HTTP header with the
client IP and the X-Forwarded-API-Key with the API Key having rate limits.
client IP and the X-Forwarded-API-Key with the API Key having rate
limits.
@param end_user_ip the end user IP (you can use both IPV4 or IPV6 syntax)
@param end_user_ip the end user IP (you can use both IPV4 or IPV6
syntax)
@param rate_limit_api_key the API key on which you have a rate limit
"""
self.headers.update({
Expand All @@ -147,9 +147,11 @@ def enable_rate_limit_forward(self, end_user_ip, rate_limit_api_key):
def set_end_user_ip(self, end_user_ip):
"""
Allow to forward an end user IP to the backend for geoip geoloc.
This option will set the X-Forwarded-For HTTP header with the client IP.
This option will set the X-Forwarded-For HTTP header with the client
IP.
@param end_user_ip the end user IP (you can use both IPV4 or IPV6 syntax)
@param end_user_ip the end user IP (you can use both IPV4 or IPV6
syntax)
"""
self.headers['X-Forwarded-For'] = end_user_ip

Expand Down Expand Up @@ -478,16 +480,16 @@ def generate_secured_api_key(self, private_api_key, queryParameters,
@param queryParameters the dict of query parameters applied to the query (used as security)
@param user_token an optional token identifying the current user
"""
if isinstance(queryParameters, (list, tuple)): #List of tags
if isinstance(queryParameters, (list, tuple)): # List of tags
queryParameters = ','.join(
map(lambda t: ''.join(['(', ','.join(t), ')']) if
isinstance(t, (list, tuple)) else t, queryParameters))
map(lambda t: ''.join(['(', ','.join(t), ')']) if
isinstance(t, (list, tuple)) else t, queryParameters))
queryParameters = {'tagFilters': queryParameters}
elif not isinstance(queryParameters, dict) and not '=' in queryParameters: #TagFilter
elif not isinstance(queryParameters, dict) and '=' not in queryParameters: # TagFilter
queryParameters = {'tagFilters': queryParameters}

if isinstance(queryParameters, dict): #New API Key generator
if user_token != None and user_token != '':
if isinstance(queryParameters, dict): # New API Key generator
if user_token is not None and user_token != '':
queryParameters['userToken'] = user_token
queryParameters = urlencode(urlify(queryParameters))

Expand Down
16 changes: 7 additions & 9 deletions algoliasearch/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights lw1
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Expand All @@ -24,16 +24,13 @@

import time

from .helpers import AlgoliaException, deprecated, safe, urlify

try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode

from .helpers import AlgoliaException
from .helpers import deprecated
from .helpers import urlify
from .helpers import safe


class IndexIterator:
"""Iterator on index."""
Expand Down Expand Up @@ -92,8 +89,9 @@ def add_object(self, content, object_id=None):
@param content contains the object to add inside the index.
The object is represented by an associative array
@param object_id (optional) an object_id you want to attribute to this object
(if the attribute already exist the old object will be overwrite)
@param object_id (optional) an object_id you want to attribute to this
object (if the attribute already exist the old object will be
overwritten)
"""
if object_id is not None:
path = '/%s' % safe(object_id)
Expand Down Expand Up @@ -920,7 +918,7 @@ def search_facet(self, facet_name, facet_query, query=None):
query = {}
query['facetQuery'] = facet_query
path = '/facets/%s/query' % safe(facet_name)
return self._req(True, path, 'POST', data={'params' : urlencode(urlify(query))})
return self._req(True, path, 'POST', data={'params': urlencode(urlify(query))})

def _req(self, is_search, path, meth, params=None, data=None):
"""Perform an HTTPS request with retry logic."""
Expand Down
8 changes: 4 additions & 4 deletions algoliasearch/transport.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os
import json
import os

from requests import Session

from .helpers import urlify, CustomJSONEncoder, AlgoliaException
from .helpers import AlgoliaException, CustomJSONEncoder, urlify

try:
from urllib import urlencode
Expand Down Expand Up @@ -82,9 +82,9 @@ def _session_req(self, host, path, meth, timeout, params, data):
if res.status_code // 100 == 4:
message = 'HTTP Code: %d' % (res.status_code)
try:
j = res.json()
j = res.json()
except:
j = { 'message': res.text}
j = {'message': res.text}
if j is not None and 'message' in j:
message = j['message']
raise AlgoliaException(message)
Expand Down
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,8 @@
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
Expand Down
10 changes: 4 additions & 6 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os
import time
from random import randint

from faker import Factory
from algoliasearch.client import Client
from algoliasearch import Client


class FakeData(object):
Expand Down Expand Up @@ -39,10 +37,10 @@ def generate_id(self):

def get_api_client():
if 'APPENGINE_RUNTIME' in os.environ:
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import urlfetch_stub
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch', urlfetch_stub.URLFetchServiceStub())
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('urlfetch', urlfetch_stub.URLFetchServiceStub())
return Client(os.environ['ALGOLIA_APPLICATION_ID'],
os.environ['ALGOLIA_API_KEY'])

Expand Down
37 changes: 13 additions & 24 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from random import randint
import time
import os
import time
import unittest
from random import randint

try:
import unittest2 as unittest # py26
except ImportError:
import unittest

from algoliasearch.client import Client, MAX_API_KEY_LENGTH
from algoliasearch.client import MAX_API_KEY_LENGTH, Client

from .helpers import safe_index_name
from .helpers import get_api_client
from .helpers import FakeData
from .helpers import FakeData, get_api_client, safe_index_name


class ClientTest(unittest.TestCase):
Expand All @@ -25,20 +17,21 @@ class ClientTest(unittest.TestCase):
def setUpClass(cls):
cls.client = get_api_client()
cls.index_name = [
safe_index_name('àlgol?à1-python{0}'.format(randint(1, 1000))),
safe_index_name('àlgol?à2-python{0}'.format(randint(1, 1000))),
safe_index_name(u'àlgol?à1-python{0}'.format(randint(1, 100000))),
safe_index_name(u'àlgol?à2-python{0}'.format(randint(1, 100000))),
]
cls.index = [cls.client.init_index(name) for name in cls.index_name]
for name in cls.index_name:
cls.client.delete_index(name)

cls.factory = FakeData()

@classmethod
def tearDownClass(cls):
for name in cls.index_name:
cls.client.delete_index(name)

def setUp(self):
for name in self.index_name:
self.client.delete_index(name)


class ClientNoDataOperationsTest(ClientTest):
"""Tests that use two index and don't make any data operations."""
Expand Down Expand Up @@ -135,14 +128,14 @@ def test_dns_timeout(self):
client.set_timeout(5, 2)

now = time.time()
indices = client.list_indexes()
client.list_indexes()
self.assertLess(now + 5, time.time())


class ClientWithDataTest(ClientTest):
"""Tests that use two index with initial data."""

def setUp(self):
super(ClientWithDataTest, self).setUp()
self.objs = [
self.factory.fake_contact(5),
self.factory.fake_contact(5)
Expand All @@ -153,10 +146,6 @@ def setUp(self):
self.index[i].wait_task(t['taskID'])
self.objectsIDs.append(t['objectIDs'])

def tearDown(self):
for index in self.index:
index.clear_index()

def test_list_indexes(self):
res = self.client.list_indexes()
res_names = [elt['name'] for elt in res['items']]
Expand Down
Loading

0 comments on commit 9e55330

Please sign in to comment.