public
Last active

  • Download Gist
spritz.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
import asynchat, asyncore, socket, base64, urllib, sys
from urlparse import urlparse
try:
import json
except ImportError:
import simplejson as json
 
USER = "test"
PASS = "test"
URL = 'http://stream.twitter.com/spritzer.json'
 
class TwitterStreamGET(asynchat.async_chat):
def __init__(self, user, pword, url):
asynchat.async_chat.__init__(self)
self.authkey = base64.b64encode("%s:%s" % (user, pword))
self.url = url
self.host = urlparse(url)[1]
try:
proxy = urlparse(urllib.getproxies()['http'])[1].split(':')
proxy[1] = int(proxy[1])
self.proxy = tuple(proxy)
except:
self.proxy = None
self.set_terminator("\r\n")
self.inbuf = ""
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
if self.proxy:
self.connect( self.proxy )
else:
self.connect( (self.host, 80) )
def collect_incoming_data(self, data):
self.inbuf += data
def found_terminator(self):
if self.inbuf.startswith("HTTP/1.0") and not self.inbuf.startswith("HTTP/1.0 2"):
print >> sys.stderr, self.inbuf
else:
try:
a = json.loads(self.inbuf)
print a['text'], '\n'
except:
pass
self.inbuf = ""
def handle_connect(self):
request = 'GET %s HTTP/1.1\r\n' % self.url
request += 'Host: %s\r\n' % self.host
request += 'Authorization: Basic %s\r\n' % self.authkey
request += 'Accept: application/json\r\n\r\n'
self.push(request)
def handle_close(self):
self.close()
 
if __name__ == '__main__':
c = TwitterStreamGET(USER, PASS, URL)
asyncore.loop()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.