streaming.py 2.4 KB
Newer Older
1
2
3
4
5
6
7
8
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE

import httplib
from threading import Thread

from . auth import BasicAuthHandler
9
10
from . parsers import parse_status
from . api import API
11
from . error import TweepError
12
13
14
15
16
17
18
19

try:
  import json
except ImportError:
  import simplejson as json

class Stream(object):

20
  def __init__(self, username, password, callback, host='stream.twitter.com', buffer_size=1500):
21
22
23
24
    self.host = host
    self.auth = BasicAuthHandler(username, password)
    self.running = False
    self.buffer_size = buffer_size
25
    self.callback = callback
26
27

  def _run(self):
28
    api = API()
29
    conn = httplib.HTTPConnection(self.host, timeout=5)
30
31
    headers = {}
    self.auth.apply_auth(None, None, headers, None)
32
    conn.request('POST', self.url, headers=headers)
33
34
35
36
37
38
39
40
    resp = conn.getresponse()
    data = ''
    while self.running:
      if resp.isclosed():
        break

      # read length
      length = ''
41
      while resp.isclosed() is False:
42
43
44
45
46
47
48
49
50
51
52
53
        c = resp.read(1)
        if c == '\n':
          break
        length += c
      length = length.strip()
      if length.isdigit():
        length = int(length)
      else:
        continue

      # read data
      data = resp.read(length)
54
55
56
57
58
59
60
61

      # turn json data into status object
      if 'in_reply_to_status_id' in data:
        status = parse_status(data, api)
        self.callback(status)

      # TODO: we should probably also parse delete/track messages
      # and pass to a callback
62
63
64
65

    conn.close()
    self.running = False

66
  def spritzer(self):
67
68
    if self.running:
      raise TweepError('Stream object already connected!')
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    self.url = '/spritzer.json?delimited=length'
    self.running = True
    Thread(target=self._run).start()

  def follow(self, follow=None):
    if self.running:
      raise TweepError('Stream object already connected!')
    self.url = '/follow.json?delimited=length'
    if follow:
      self.url += '&follow=%s' % str(follow).strip('[]').replace(' ', '')
    self.running = True
    Thread(target=self._run).start()

  def track(self, track=None):
    if self.running:
      raise TweepError('Stream object already connected!')
    self.url = '/track.json?delimited=length'
    if track:
      self.url += '&track=%s' % str(track).strip('[]').replace(' ', '')
88
89
90
91
    self.running = True
    Thread(target=self._run).start()
    
  def disconnect(self):
92
93
    if self.running is False:
      return
94
95
    self.running = False