Created
May 2, 2015 19:14
-
-
Save yamatt/a454ea5fa841b981c5ea to your computer and use it in GitHub Desktop.
Twitter Streaming Example
This file contains hidden or 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
pip install requests requests_oauthlib |
This file contains hidden or 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
from requests_oauthlib import OAuth1Session | |
import json | |
import requests | |
CONSUMER_KEY = "..." | |
CONSUMER_SECRET = "..." | |
ACCESS_TOKEN = "..." | |
TOKEN_SECRET = "..." | |
STREAM_URL = "https://stream.twitter.com/1.1/statuses/filter.json" | |
def get_client(): | |
return OAuth1Session(CONSUMER_KEY, | |
client_secret=CONSUMER_SECRET, | |
resource_owner_key=ACCESS_TOKEN, | |
resource_owner_secret=TOKEN_SECRET | |
) | |
def get_response(client, **filter_data): | |
return client.post( | |
STREAM_URL, | |
data=filter_data, | |
stream=True | |
) | |
def print_lines(r): | |
for line in r.iter_lines(): | |
if line: # filter out keep-alive new lines | |
print json.loads(line) | |
if __name__ == "__main__": | |
client = get_client() | |
r = get_response(client, track="@sw_trains") | |
print_lines(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment