]> jfr.im git - z_archive/twitter.git/blob - twitter/stream.py
Stream example and some fixes for py27. Breaks in py3 probably.
[z_archive/twitter.git] / twitter / stream.py
1 try:
2 import urllib.request as urllib_request
3 import urllib.error as urllib_error
4 except ImportError:
5 import urllib2 as urllib_request
6 import urllib2 as urllib_error
7 import json
8
9 from .api import TwitterCall, wrap_response
10
11 class TwitterJSONIter(object):
12
13 def __init__(self, handle, uri, arg_data):
14 self.decoder = json.JSONDecoder()
15 self.handle = handle
16 self.buf = ""
17
18 def __iter__(self):
19 while True:
20 # This might need better py3 IO
21 self.buf += self.handle.read(1024)
22 try:
23 res, ptr = self.decoder.raw_decode(self.buf)
24 self.buf = self.buf[ptr + 2:] # +2 is for \r\n
25 yield wrap_response(res, self.handle.headers)
26 except ValueError as e:
27 continue
28 except urllib_error.HTTPError as e:
29 raise TwitterHTTPError(e, uri, self.format, arg_data)
30
31 class TwitterStreamCall(TwitterCall):
32 def _handle_response(self, req, uri, arg_data):
33 handle = urllib_request.urlopen(req,)
34 return iter(TwitterJSONIter(handle, uri, arg_data))
35
36 class TwitterStream(TwitterStreamCall):
37 def __init__(
38 self, domain="stream.twitter.com", secure=False, auth=None,
39 api_version='1'):
40 uriparts = ()
41 uriparts += (str(api_version),)
42
43 TwitterStreamCall.__init__(
44 self, auth=auth, format="json", domain=domain,
45 callable_cls=TwitterStreamCall,
46 secure=secure, uriparts=uriparts)