Skip to content

Commit 5635c17

Browse files
committed
Merge remote-tracking branch 'origin/master' into feature/test-tlc
Conflicts: stream/tests.py
2 parents a770d49 + 53faf24 commit 5635c17

8 files changed

Lines changed: 363 additions & 43 deletions

File tree

‎.travis.yml‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,9 @@ python:
77
- 3.4
88
- 3.5
99
- 3.6
10-
# These are allowed to fail
11-
- '3.5-dev' # 3.5 development branch
12-
- '3.6-dev' # 3.6 development branch
13-
- 'nightly' # currently points to 3.7-dev
14-
- 'pypy'
15-
- 'pypy3.3-5.2-alpha1'
1610

1711
matrix:
1812
fast_finish: true
19-
allow_failures:
20-
- python: '3.5-dev' # 3.5 development branch
21-
- python: '3.6-dev' # 3.6 development branch
22-
- python: 'nightly'
23-
- python: 'pypy'
24-
- python: 'pypy3.3-5.2-alpha1'
2513

2614
cache: pip
2715
notifications:

‎CHANGELOG‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,35 @@
22
Change history
33
================
44

5+
=======
6+
2.7.0
7+
======
8+
:release-date: 2017-12-14
9+
:by: Aaron McMillin
10+
11+
* All client methods that make requests will return the response
12+
13+
2.6.2
14+
=====
15+
:release-date 2017-12-08
16+
:by: Balazs
17+
18+
Consolidate API URL generation across API, Collections and Personalization services
19+
20+
2.6.0
21+
=====
22+
:release-date 2017-12-08
23+
:by: Balazs
24+
25+
Support the new collections endpoint and flexible get requests for personalization
26+
27+
2.5.0
28+
======
29+
:release-date: 2017-10-19
30+
:by: Tommaso Barbugli
31+
32+
* Use new .com domain for API and Analytics
33+
534
2.4.0
635
======
736
:release-date: 2017-08-31

‎setup.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,18 @@
2626
.. _`Github`: https://github.com/GetStream/stream-python
2727
'''
2828

29+
requests = 'requests>=2.3.0,<3'
30+
31+
if sys.version_info < (2, 7, 9):
32+
requests = 'requests[security]>=2.4.1,<3'
33+
2934
install_requires = [
3035
'pyjwt==1.3.0',
31-
'requests>=2.2.1',
36+
requests,
3237
'six>=1.8.0',
3338
'httpsig==1.1.2'
3439
]
3540

36-
3741
class PyTest(TestCommand):
3842

3943
def finalize_options(self):

‎stream/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
__copyright__ = 'Copyright 2014, Stream.io, Inc'
66
__credits__ = ['Thierry Schellenbach, mellowmorning.com, @tschellenbach']
77
__license__ = 'BSD-3-Clause'
8-
__version__ = '2.4.0'
8+
__version__ = '2.7.0'
99
__maintainer__ = 'Thierry Schellenbach'
1010
__email__ = 'support@getstream.io'
1111
__status__ = 'Production'
@@ -29,7 +29,7 @@ def connect(api_key=None, api_secret=None, app_id=None, version='v1.0',
2929
result = pattern.match(stream_url)
3030
if result and len(result.groups()) == 4:
3131
api_key, api_secret, location, app_id = result.groups()
32-
location = None if location == 'getstream' else location
32+
location = None if location in ('getstream', 'stream-io-api') else location
3333
else:
3434
raise ValueError('Invalid api key or heroku url')
3535

‎stream/client.py‎

Lines changed: 57 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,15 @@
1212
from stream.utils import validate_feed_slug, validate_user_id
1313
from requests import Request
1414

15+
try:
16+
from urllib.parse import urlparse
17+
except ImportError:
18+
from urlparse import urlparse
1519

1620
logger = logging.getLogger(__name__)
1721

1822

1923
class StreamClient(object):
20-
base_url = 'https://api.getstream.io/api/'
2124

2225
def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=6.0, base_url=None, location=None):
2326
'''
@@ -51,20 +54,39 @@ def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=6.0, bas
5154
self.timeout = timeout
5255
self.location = location
5356

57+
self.base_domain_name = 'stream-io-api.com'
58+
self.api_location = location
59+
self.custom_api_port = None
60+
self.protocol = 'https'
61+
5462
if os.environ.get('LOCAL'):
55-
self.base_url = 'http://localhost:8000/api/'
63+
self.base_domain_name = 'localhost'
64+
self.protocol = 'http'
65+
self.custom_api_port = 8000
5666
self.timeout = 20
5767
elif base_url is not None:
58-
self.base_url = base_url
68+
parsed_url = urlparse(base_url)
69+
self.base_domain_name = parsed_url.hostname
70+
self.protocol = parsed_url.scheme
71+
self.custom_api_port = parsed_url.port
72+
self.api_location = ""
5973
elif location is not None:
60-
self.base_url = 'https://%s-api.getstream.io/api/' % location
74+
self.location = location
6175

62-
self.base_analytics_url = 'https://analytics.getstream.io/analytics/'
76+
self.base_analytics_url = 'https://analytics.stream-io-api.com/analytics/'
6377

6478
self.session = requests.Session()
65-
# TODO: turn this back on after we verify it doesnt retry on slower requests
66-
self.session.mount(self.base_url, HTTPAdapter(max_retries=0))
6779
self.auth = HTTPSignatureAuth(api_key, secret=api_secret)
80+
81+
# setup personalization
82+
from stream.personalization import Personalization
83+
token = self.create_jwt_token('personalization', '*', feed_id='*', user_id='*')
84+
self.personalization = Personalization(self, token)
85+
# setup the collection
86+
from stream.collections import Collections
87+
token = self.create_jwt_token('collections', '*', feed_id='*', user_id='*')
88+
self.collections = Collections(self, token)
89+
6890

6991
def feed(self, feed_slug, user_id):
7092
'''
@@ -97,8 +119,23 @@ def get_default_header(self):
97119
}
98120
return base_headers
99121

100-
def get_full_url(self, relative_url):
101-
url = self.base_url + self.version + '/' + relative_url
122+
def get_full_url(self, service_name, relative_url):
123+
if self.api_location:
124+
hostname = '%s-%s.%s' % (self.api_location, service_name, self.base_domain_name)
125+
elif service_name:
126+
hostname = '%s.%s' % (service_name, self.base_domain_name)
127+
else:
128+
hostname = self.base_domain_name
129+
130+
if self.base_domain_name == 'localhost':
131+
hostname = 'localhost'
132+
133+
base_url = "%s://%s" % (self.protocol, hostname)
134+
135+
if self.custom_api_port:
136+
base_url = "%s:%s" % (base_url, self.custom_api_port)
137+
138+
url = base_url + '/' + service_name + '/' + self.version + '/' + relative_url
102139
return url
103140

104141
def get_user_agent(self):
@@ -125,7 +162,7 @@ def _make_signed_request(self, method_name, relative_url, params=None, data=None
125162
headers['Date'] = date_header
126163
default_params = self.get_default_params()
127164
default_params.update(params)
128-
url = self.get_full_url(relative_url)
165+
url = self.get_full_url('api', relative_url)
129166
serialized = serializer.dumps(data)
130167
method = getattr(self.session, method_name)
131168
if method_name in ['post', 'put']:
@@ -151,7 +188,7 @@ def create_jwt_token(self, resource, action, feed_id=None, user_id=None):
151188
payload['user_id'] = user_id
152189
return jwt.encode(payload, self.api_secret).decode("utf-8")
153190

154-
def _make_request(self, method, relative_url, signature, params=None, data=None):
191+
def _make_request(self, method, relative_url, signature, service_name='api', params=None, data=None):
155192
params = params or {}
156193
data = data or {}
157194
serialized = None
@@ -160,8 +197,13 @@ def _make_request(self, method, relative_url, signature, params=None, data=None)
160197
headers = self.get_default_header()
161198
headers['Authorization'] = signature
162199
headers['stream-auth-type'] = 'jwt'
163-
url = self.get_full_url(relative_url)
164-
if method.__name__ in ['post', 'put']:
200+
201+
if not relative_url.endswith('/'):
202+
relative_url += '/'
203+
204+
url = self.get_full_url(service_name, relative_url)
205+
206+
if method.__name__ in ['post', 'put', 'delete']:
165207
serialized = serializer.dumps(data)
166208
response = method(url, data=serialized, headers=headers,
167209
params=default_params, timeout=self.timeout)
@@ -236,7 +278,7 @@ def add_to_many(self, activity, feeds):
236278
237279
'''
238280
data = {'activity': activity, 'feeds': feeds}
239-
self._make_signed_request('post', 'feed/add_to_many/', data=data)
281+
return self._make_signed_request('post', 'feed/add_to_many/', data=data)
240282

241283
def follow_many(self, follows, activity_copy_limit=None):
242284
'''
@@ -251,7 +293,7 @@ def follow_many(self, follows, activity_copy_limit=None):
251293
if activity_copy_limit != None:
252294
params = dict(activity_copy_limit=activity_copy_limit)
253295

254-
self._make_signed_request('post', 'follow_many/', params=params, data=follows)
296+
return self._make_signed_request('post', 'follow_many/', params=params, data=follows)
255297

256298
def update_activities(self, activities):
257299
'''

‎stream/collections.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
class Collections(object):
2+
3+
def __init__(self, client, token):
4+
"""
5+
Used to manipulate data at the 'meta' endpoint
6+
:param client: the api client
7+
:param token: the token
8+
"""
9+
10+
self.client = client
11+
self.token = token
12+
13+
def upsert(self, collection_name, data):
14+
"""
15+
"Insert new or update existing data.
16+
:param collection_name: Collection Name i.e 'user'
17+
:param data: list of dictionaries
18+
:return: http response, 201 if successful along with data posted.
19+
20+
**Example**::
21+
client.collection.upsert('user', [{"id": '1', "name": "Juniper", "hobbies": ["Playing", "Sleeping", "Eating"]},
22+
{"id": '2', "name": "Ruby", "interests": ["Sunbeams", "Surprise Attacks"]}])
23+
"""
24+
25+
if type(data) != list:
26+
data = [data]
27+
28+
data_json = {collection_name: data}
29+
30+
response = self.client.post('meta/', service_name='api',
31+
signature=self.token, data={'data': data_json})
32+
return response
33+
34+
def select(self, collection_name, ids):
35+
"""
36+
Retrieve data from meta endpoint, can include data you've uploaded or personalization/analytic data
37+
created by the stream team.
38+
:param collection_name: Collection Name i.e 'user'
39+
:param ids: list of ids of feed group i.e [123,456]
40+
:return: meta data as json blob
41+
42+
**Example**::
43+
client.collection.select('user', 1)
44+
client.collection.select('user', [1,2,3])
45+
"""
46+
47+
if type(ids) != list:
48+
ids = [ids]
49+
ids = [str(i) for i in ids]
50+
51+
foreign_ids = []
52+
for i in range(len(ids)):
53+
foreign_ids.append('%s:%s' % (collection_name, ids[i]))
54+
foreign_ids = ','.join(foreign_ids)
55+
56+
response = self.client.get('meta/', service_name='api', params={'foreign_ids': foreign_ids},
57+
signature=self.token)
58+
59+
return response
60+
61+
def delete(self, collection_name, ids):
62+
"""
63+
Delete data from meta.
64+
:param collection_name: Collection Name i.e 'user'
65+
:param ids: list of ids to delete i.e [123,456]
66+
:return: data that was deleted if if successful or not.
67+
68+
**Example**::
69+
client.collections.delete('user', '1')
70+
collections.delete('user', ['1','2','3'])
71+
"""
72+
73+
if type(ids) != list:
74+
ids = [ids]
75+
ids = [str(i) for i in ids]
76+
77+
data = {'collection_name': collection_name, 'ids': ids}
78+
79+
response = self.client.delete('meta/', service_name='api', data=data,
80+
signature=self.token)
81+
82+
return response

‎stream/personalization.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Personalization(object):
2+
def __init__(self, client, token):
3+
"""
4+
Methods to interact with personalized feeds.
5+
:param client: the api client
6+
:param token: the token
7+
"""
8+
9+
self.client = client
10+
self.token = token
11+
12+
def get(self, resource, **params):
13+
"""
14+
Get personalized activities for this feed
15+
:param resource: personalized resource endpoint i.e "follow_recommendations"
16+
:param params: params to pass to url i.e user_id = "user:123"
17+
:return: personalized feed
18+
19+
**Example**::
20+
personalization.get('follow_recommendations', user_id=123, limit=10, offset=10)
21+
"""
22+
23+
response = self.client.get(resource, service_name='personalization', params=params,
24+
signature=self.token)
25+
return response
26+
27+
def post(self, resource, **params):
28+
"""
29+
"Generic function to post data to personalization endpoint
30+
:param resource: personalized resource endpoint i.e "follow_recommendations"
31+
:param params: params to pass to url (data is a reserved keyword to post to body)
32+
33+
34+
**Example**::
35+
#Accept or reject recommendations.
36+
personalization.post('follow_recommendations', user_id=123, accepted=[123,345],
37+
rejected=[456])
38+
"""
39+
40+
data = params['data'] or None
41+
42+
response = self.client.post(resource, service_name='personalization', params=params,
43+
signature=self.token, data=data)
44+
return response
45+
46+
def delete(self, resource, **params):
47+
"""
48+
shortcut to delete metadata or activites
49+
:param resource: personalized url endpoint typical "meta"
50+
:param params: params to pass to url i.e user_id = "user:123"
51+
:return: data that was deleted if if successful or not.
52+
"""
53+
54+
response = self.client.delete(resource, service_name='personalization', params=params,
55+
signature=self.token)
56+
57+
return response

0 commit comments

Comments
 (0)