Skip to content

Commit 424558a

Browse files
committed
initial commit python stream client
1 parent e2c58b8 commit 424558a

10 files changed

Lines changed: 615 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
stream-python
2-
=============
1+
Stream client
2+
-------------
3+
4+
5+
6+
## Running tests ##
7+
8+
py.test stream/tests.py
39

4-
Python client for Stream

‎fabfile.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
from fabric.api import local, cd
2+
import os
3+
import time
4+
import datetime
5+
from fabric.operations import sudo
6+
from fabric.state import env
7+
from fabric.context_managers import settings
8+
9+
10+
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
11+
manage_py = os.path.join(PROJECT_ROOT, 'manage.py')
12+
13+
env.hosts = ['getstream.io']
14+
15+
env.user = 'stream'
16+
env.forward_agent = True
17+
18+
19+
def publish(test='no'):
20+
'''
21+
The whole merging stuff etc
22+
'''
23+
if test == 'yes':
24+
validate()
25+
tag = get_new_tag()
26+
time.sleep(1)
27+
merge_master()
28+
local('git tag %s' % tag)
29+
local('git push origin production %s' % tag)
30+
time.sleep(1)
31+
local('git checkout master')
32+
33+
34+
def merge_master():
35+
# update our local data
36+
local('git fetch --all')
37+
time.sleep(1)
38+
# update with the changes
39+
local('git checkout production')
40+
time.sleep(1)
41+
# merge the remote branch
42+
local('git merge origin/production')
43+
time.sleep(1)
44+
# now merge master
45+
local('git merge origin/master')
46+
47+
48+
def get_new_tag():
49+
tag_command = local('git tag', capture=True)
50+
51+
tags = [l.strip().replace('_', '-')
52+
for l in tag_command.split('\n') if l.startswith('20')]
53+
tags_dict = dict.fromkeys(tags)
54+
tag_format = unicode(datetime.date.today()) + '-v%s'
55+
version = 1
56+
57+
while tag_format % version in tags_dict:
58+
version += 1
59+
60+
new_tag = tag_format % version
61+
62+
return new_tag
63+
64+
65+
def validate():
66+
with cd(PROJECT_ROOT):
67+
local(
68+
'pep8 --exclude=migrations --ignore=E501,E225 .')
69+
local('%s test' % manage_py)
70+
71+
def clean():
72+
# all dirs which contain python code
73+
python_dirs = []
74+
for root, dirs, files in os.walk(PROJECT_ROOT):
75+
python_dir = any(f.endswith('.py') for f in files)
76+
if python_dir:
77+
python_dirs.append(root)
78+
for d in python_dirs:
79+
print d
80+
local('bash -c "autopep8 -i %s/*.py"' % d)
81+
82+
83+
84+
def docs():
85+
local('sphinx-build -Eav docs_public html')
86+
local('python manage.py build_docs')

‎setup.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python
2+
3+
4+
from setuptools import setup, find_packages
5+
from setuptools.command.test import test as TestCommand
6+
from feedly import __version__, __maintainer__, __email__
7+
import sys
8+
9+
long_description = open('README.md').read()
10+
11+
tests_require = [
12+
'mock',
13+
'pep8',
14+
'unittest2',
15+
'pytest',
16+
]
17+
18+
install_requires = [
19+
'requests',
20+
]
21+
22+
23+
class PyTest(TestCommand):
24+
25+
def finalize_options(self):
26+
TestCommand.finalize_options(self)
27+
self.test_args = []
28+
self.test_suite = True
29+
30+
def run_tests(self):
31+
# import here, cause outside the eggs aren't loaded
32+
import pytest
33+
errno = pytest.main(self.test_args)
34+
sys.exit(errno)
35+
36+
setup(
37+
name='stream-python',
38+
version=__version__,
39+
author=__maintainer__,
40+
author_email=__email__,
41+
url='http://github.com/tschellenbach/stream-python',
42+
description='Client for getstream.io. Build scalable newsfeeds & activity streams in a few hours instead of weeks.',
43+
long_description=long_description,
44+
packages=find_packages(),
45+
zip_safe=False,
46+
install_requires=install_requires,
47+
extras_require={'test': tests_require},
48+
cmdclass={'test': PyTest},
49+
tests_require=tests_require,
50+
include_package_data=True,
51+
classifiers=[
52+
'Intended Audience :: Developers',
53+
'Intended Audience :: System Administrators',
54+
'Operating System :: OS Independent',
55+
'Topic :: Software Development',
56+
'Development Status :: 5 - Production/Stable',
57+
'License :: OSI Approved :: GNU General Public License (GPL)',
58+
'Natural Language :: English',
59+
'Programming Language :: Python',
60+
'Topic :: Scientific/Engineering :: Mathematics',
61+
'Topic :: Software Development :: Libraries :: Python Modules',
62+
],
63+
)

‎stream/__init__.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
__author__ = 'Thierry Schellenbach'
3+
__copyright__ = 'Copyright 2012, Thierry Schellenbach'
4+
__credits__ = ['Thierry Schellenbach, mellowmorning.com, @tschellenbach']
5+
__license__ = 'BSD'
6+
__version__ = '0.1.0'
7+
__maintainer__ = 'Thierry Schellenbach'
8+
__email__ = 'thierryschellenbach@gmail.com'
9+
__status__ = 'Production'
10+
11+
12+
def connect(api_key, api_secret):
13+
'''
14+
Returns a Client object
15+
16+
:param api_key: your api key
17+
:param api_secret: the api secret
18+
'''
19+
from stream.client import StreamClient
20+
return StreamClient(api_key, api_secret)
21+
22+
23+
'''
24+
TODO:
25+
26+
Simplify signing (tommaso please check)
27+
pk_gt and pk_gte seems to have the same output (pk_gt doesnt always work)
28+
follow functionality doesnt work
29+
30+
Test coverage
31+
Documentation
32+
Pypi entry
33+
Github
34+
Read the docs
35+
Travis setup
36+
'''

‎stream/client.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import requests
2+
from stream import exceptions
3+
import logging
4+
from stream.signing import StreamSigner
5+
from stream.utils import validate_feed
6+
from simplejson.scanner import JSONDecodeError
7+
8+
logger = logging.getLogger(__name__)
9+
10+
11+
class StreamClient(object):
12+
base_url = 'https://getstream.io/api/'
13+
# base_url = 'http://localhost:8000/api/'
14+
15+
def __init__(self, api_key, api_secret):
16+
'''
17+
Initialize the client with the given api key and secret
18+
19+
:param api_key: the api key
20+
:param api_secret: the api secret
21+
22+
**Example usage**::
23+
24+
import stream
25+
# initialize the client
26+
client = stream.connect('key', 'secret')
27+
# get a feed object
28+
feed = client.feed('aggregated:1')
29+
# write data to the feed
30+
activity_data = {'actor': 1, 'verb': 'tweet', 'object': 1}
31+
activity_id = feed.add_activity(activity_data)['id']
32+
activities = feed.get()
33+
34+
feed.follow('flat:3')
35+
activities = feed.get()
36+
feed.unfollow('flat:3')
37+
feed.remove_activity(activity_id)
38+
'''
39+
self.api_key = api_key
40+
self.api_secret = api_secret
41+
42+
def feed(self, feed_id):
43+
'''
44+
Returns a Feed object
45+
46+
:param feed_id: the feed object
47+
'''
48+
validate_feed(feed_id)
49+
from stream.feed import Feed
50+
return Feed(self, feed_id)
51+
52+
def get_default_params(self):
53+
'''
54+
Returns the params with the API key present
55+
'''
56+
params = dict(api_key=self.api_key)
57+
return params
58+
59+
def get_headers(self, feed):
60+
'''
61+
Returns the headers with the signed authorization key
62+
'''
63+
feed = feed.replace(':','')
64+
signature = StreamSigner(secret=self.api_secret).signature(feed)
65+
headers = {'Authorization': '%s %s' % (feed, signature)}
66+
print headers
67+
return headers
68+
69+
def _make_request(self, method, relative_url, feed, params=None, data=None):
70+
params = params or {}
71+
data = data or {}
72+
73+
default_params = self.get_default_params()
74+
default_params.update(params)
75+
76+
headers = self.get_headers(feed)
77+
url = self.base_url + relative_url
78+
79+
logger.debug('stream api call %s, headers %s params %s data %s', url, headers, default_params, data)
80+
print default_params
81+
response = method(url, data=data, headers=headers, params=default_params)
82+
try:
83+
result = response.json()
84+
except JSONDecodeError, e:
85+
print 'couldnt not parse json "%s"' % response.text
86+
1/0
87+
if result.get('exception'):
88+
self.raise_exception(result)
89+
return result
90+
91+
def raise_exception(self, result):
92+
'''
93+
Map the exception code to an exception class and raise it
94+
'''
95+
from stream.exceptions import get_exception_dict
96+
error_message = result['detail']
97+
error_code = result.get('code')
98+
exception_dict = get_exception_dict()
99+
exception_class = exception_dict.get(error_code, exceptions.StreamApiException)
100+
exception = exception_class(error_message)
101+
raise exception
102+
103+
def post(self, *args, **kwargs):
104+
'''
105+
Shortcut for make request
106+
'''
107+
return self._make_request(requests.post, *args, **kwargs)
108+
109+
def get(self, *args, **kwargs):
110+
'''
111+
Shortcut for make request
112+
'''
113+
return self._make_request(requests.get, *args, **kwargs)
114+
115+
def delete(self, *args, **kwargs):
116+
'''
117+
Shortcut for make request
118+
'''
119+
return self._make_request(requests.delete, *args, **kwargs)

0 commit comments

Comments
 (0)