Skip to content

Commit efedf22

Browse files
committed
add http signature auth method, add many and follow many
1 parent 3605f81 commit efedf22

3 files changed

Lines changed: 103 additions & 18 deletions

File tree

‎setup.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828

2929
install_requires = [
3030
'requests>=2.3.0',
31-
'six>=1.8.0'
31+
'six>=1.8.0',
32+
'httpsig==1.1.0'
3233
]
3334

3435

‎stream/client.py‎

Lines changed: 67 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
from datetime import datetime
12
from requests.adapters import HTTPAdapter
23
from stream import exceptions, serializer
34
from stream.signing import sign
45
import logging
56
import os
67
import requests
78
from stream.utils import validate_feed_slug, validate_user_id
9+
from httpsig.requests_auth import HTTPSignatureAuth
810

911

1012
logger = logging.getLogger(__name__)
@@ -13,7 +15,7 @@
1315
class StreamClient(object):
1416
base_url = 'https://api.getstream.io/api/'
1517

16-
def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=3.0, base_url=None, location=None):
18+
def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=6.0, base_url=None, location=None):
1719
'''
1820
Initialize the client with the given api key and secret
1921
@@ -45,17 +47,18 @@ def __init__(self, api_key, api_secret, app_id, version='v1.0', timeout=3.0, bas
4547
self.timeout = timeout
4648
self.location = location
4749

48-
if base_url is not None:
50+
if os.environ.get('LOCAL'):
51+
self.base_url = 'http://localhost:8000/api/'
52+
self.timeout = 20
53+
elif base_url is not None:
4954
self.base_url = base_url
5055
elif location is not None:
5156
self.base_url = 'https://%s-api.getstream.io/api/' % location
52-
elif os.environ.get('LOCAL'):
53-
self.base_url = 'http://localhost:8000/api/'
54-
self.timeout = 20
55-
57+
5658
self.session = requests.Session()
5759
# TODO: turn this back on after we verify it doesnt retry on slower requests
5860
self.session.mount(self.base_url, HTTPAdapter(max_retries=0))
61+
self.auth = HTTPSignatureAuth(api_key, secret=api_secret)
5962

6063
def feed(self, feed_slug, user_id):
6164
'''
@@ -81,6 +84,13 @@ def get_default_params(self):
8184
params = dict(api_key=self.api_key)
8285
return params
8386

87+
def get_default_header(self):
88+
base_headers = {
89+
'Content-type': 'application/json',
90+
'User-Agent': self.get_user_agent()
91+
}
92+
return base_headers
93+
8494
def get_full_url(self, relative_url):
8595
url = self.base_url + self.version + '/' + relative_url
8696
return url
@@ -90,27 +100,47 @@ def get_user_agent(self):
90100
agent = 'stream-python-client-%s' % __version__
91101
return agent
92102

103+
def _parse_response(self, response):
104+
try:
105+
parsed_result = serializer.loads(response.text)
106+
except ValueError:
107+
parsed_result = None
108+
if parsed_result is None or parsed_result.get('exception') or response.status_code >= 500:
109+
self.raise_exception(parsed_result, status_code=response.status_code)
110+
return parsed_result
111+
112+
def _make_signed_request(self, method_name, relative_url, params=None, data=None):
113+
params = params or {}
114+
data = data or {}
115+
headers = self.get_default_header()
116+
headers['X-Api-Key'] = self.api_key
117+
date_header = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
118+
headers['Date'] = date_header
119+
default_params = self.get_default_params()
120+
default_params.update(params)
121+
url = self.get_full_url(relative_url)
122+
serialized = serializer.dumps(data)
123+
method = getattr(self.session, method_name)
124+
response = method(url, auth=self.auth, data=serialized, headers=headers,
125+
params=default_params, timeout=self.timeout)
126+
logger.debug('stream api call %s, headers %s data %s',
127+
response.url, headers, data)
128+
return self._parse_response(response)
129+
93130
def _make_request(self, method, relative_url, signature, params=None, data=None):
94131
params = params or {}
95132
data = data or {}
96133
default_params = self.get_default_params()
97134
default_params.update(params)
98-
headers = {'Authorization': signature}
99-
headers['Content-type'] = 'application/json'
100-
headers['User-Agent'] = self.get_user_agent()
135+
headers = self.get_default_header()
136+
headers['Authorization'] = signature
101137
url = self.get_full_url(relative_url)
102138
serialized = serializer.dumps(data)
103139
response = method(url, data=serialized, headers=headers,
104140
params=default_params, timeout=self.timeout)
105141
logger.debug('stream api call %s, headers %s data %s',
106142
response.url, headers, data)
107-
try:
108-
parsed_result = serializer.loads(response.text)
109-
except ValueError:
110-
parsed_result = None
111-
if parsed_result is None or parsed_result.get('exception') or response.status_code >= 500:
112-
self.raise_exception(parsed_result, status_code=response.status_code)
113-
return parsed_result
143+
return self._parse_response(response)
114144

115145
def raise_exception(self, result, status_code):
116146
'''
@@ -157,3 +187,24 @@ def delete(self, *args, **kwargs):
157187
Shortcut for make request
158188
'''
159189
return self._make_request(self.session.delete, *args, **kwargs)
190+
191+
def add_to_many(self, activity, feeds):
192+
'''
193+
Adds an activity to many feeds
194+
195+
:param activity: the activity data
196+
:param feeds: the list of follows (eg. ['feed:1', 'feed:2'])
197+
198+
'''
199+
data = {'activity': activity, 'feeds': feeds}
200+
self._make_signed_request('post', 'feed/add_to_many/', data=data)
201+
202+
def follow_many(self, follows):
203+
'''
204+
Creates many follows
205+
:param follows: the list of follow relations
206+
207+
eg. [{'source': source, 'target': target}]
208+
209+
'''
210+
self._make_signed_request('post', 'follow_many/', data=follows)

‎stream/tests.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def connect_debug():
1818
location='us-east'
1919
)
2020

21-
random_postfix = str(random.randint(0, 1000000))
21+
random_postfix = str(int(time.time()))
2222
client = connect_debug()
2323

2424

@@ -577,3 +577,36 @@ def test_serialization(self):
577577
serialized = serializer.dumps(data)
578578
loaded = serializer.loads(serialized)
579579
self.assertEqual(data, loaded)
580+
581+
def test_signed_request_post(self):
582+
self.c._make_signed_request('post', 'test/auth/digest/', {}, {})
583+
584+
def test_signed_request_get(self):
585+
self.c._make_signed_request('post', 'test/auth/digest/', {}, {})
586+
587+
def test_follow_many(self):
588+
sources = [getfeed('user', str(i)).id for i in range(10)]
589+
targets = [getfeed('flat', str(i)).id for i in range(10)]
590+
feeds = [{'source': s, 'target': t} for s,t in zip(sources, targets)]
591+
self.c.follow_many(feeds)
592+
593+
for target in targets:
594+
follows = self.c.feed(*target.split(':')).followers()['results']
595+
self.assertEqual(len(follows), 1)
596+
self.assertIn(follows[0]['feed_id'], sources)
597+
self.assertEqual(follows[0]['target_id'], target)
598+
599+
for source in sources:
600+
follows = self.c.feed(*source.split(':')).following()['results']
601+
self.assertEqual(len(follows), 1)
602+
self.assertEqual(follows[0]['feed_id'], source)
603+
self.assertIn(follows[0]['target_id'], targets)
604+
605+
def test_add_to_many(self):
606+
activity = {'actor': 1, 'verb': 'tweet', 'object': 1, 'custom': 'data'}
607+
feeds = [getfeed('flat', str(i)).id for i in range(10, 20)]
608+
self.c.add_to_many(activity, feeds)
609+
610+
for feed in feeds:
611+
feed = self.c.feed(*feed.split(':'))
612+
self.assertEqual(feed.get()['results'][0]['custom'], 'data')

0 commit comments

Comments
 (0)