Skip to content

Instantly share code, notes, and snippets.

@tyrion
Created June 17, 2015 12:36
Show Gist options
  • Save tyrion/dfd6cc3a9dcb148e9219 to your computer and use it in GitHub Desktop.
Save tyrion/dfd6cc3a9dcb148e9219 to your computer and use it in GitHub Desktop.
Simple Interface to Twitter APIs
import json
import logging
import os
import traceback
from contextlib import closing
import requests
from requests_oauthlib import OAuth1
STREAM_API_URL = 'https://stream.twitter.com/1.1/'
API_URL = 'https://api.twitter.com/1.1/'
auth = OAuth1(
os.environ['TWITTER_CONSUMER_KEY'],
os.environ['TWITTER_CONSUMER_SECRET'],
os.environ['TWITTER_OAUTH_TOKEN'],
os.environ['TWITTER_OAUTH_SECRET']
)
logger = logging.getLogger('twitter.stream')
def stream_api(method, **params):
with closing(requests.post(STREAM_API_URL + method,
auth=auth, params=params, stream=True)) as r:
for line in r.iter_lines():
if not line:
continue
try:
tweet = json.loads(line)
if not 'text' in tweet:
logger.warning('Unhandled message: %s', line)
else:
yield tweet
#parse_tweet(tweet).save()
except Exception, e:
traceback.print_exc()
def rest_api(method, **params):
r = requests.get(API_URL + method, auth=auth, params=params)
return r.json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment