Created
June 15, 2009 19:21
-
-
Save atl/130280 to your computer and use it in GitHub Desktop.
(Code moved to: http://github.com/atl/twitstream )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code moved to http://github.com/atl/twitstream/ | |
# Minimal python asynchronous http client that does non-authenticating | |
# proxies and http basic authorization. Intended as a proof of concept | |
# to access Twitter's streaming API: | |
# http://apiwiki.twitter.com/Streaming-API-Documentation | |
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 | |
elif self.inbuf.startswith('{'): | |
a = json.loads(self.inbuf) | |
print a['text'], '\n' | |
self.inbuf = "" | |
def handle_connect(self): | |
request = 'GET %s HTTP/1.1\r\n' % self.url | |
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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment