Fhernd

twitterstream.py

Mar 27th, 2015
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import oauth2 as oauth
  2. import urllib2 as urllib
  3.  
  4. api_key = "TWITTER_API_KEY"
  5. api_secret = "TWITTER_API_SECRET"
  6. access_token_key = "TWITTER_ACCESS_TOKEN_KEY"
  7. access_token_secret = "ACCESS_TOKEN_SECRET"
  8.  
  9. _debug = 0
  10.  
  11. oauth_token    = oauth.Token(key=access_token_key, secret=access_token_secret)
  12. oauth_consumer = oauth.Consumer(key=api_key, secret=api_secret)
  13.  
  14. signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
  15.  
  16. http_method = "GET"
  17.  
  18.  
  19. http_handler  = urllib.HTTPHandler(debuglevel=_debug)
  20. https_handler = urllib.HTTPSHandler(debuglevel=_debug)
  21.  
  22. '''
  23. Construct, sign, and open a twitter request
  24. using the hard-coded credentials above.
  25. '''
  26. def twitterreq(url, method, parameters):
  27.   req = oauth.Request.from_consumer_and_token(oauth_consumer,
  28.                                              token=oauth_token,
  29.                                              http_method=http_method,
  30.                                              http_url=url,
  31.                                              parameters=parameters)
  32.  
  33.   req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
  34.  
  35.   headers = req.to_header()
  36.  
  37.   if http_method == "POST":
  38.     encoded_post_data = req.to_postdata()
  39.   else:
  40.     encoded_post_data = None
  41.     url = req.to_url()
  42.  
  43.   opener = urllib.OpenerDirector()
  44.   opener.add_handler(http_handler)
  45.   opener.add_handler(https_handler)
  46.  
  47.   response = opener.open(url, encoded_post_data)
  48.  
  49.   return response
  50.  
  51. def fetchsamples():
  52.   url = "https://stream.twitter.com/1/statuses/sample.json"
  53.   parameters = []
  54.   response = twitterreq(url, "GET", parameters)
  55.   for line in response:
  56.     print line.strip()
  57.  
  58. if __name__ == '__main__':
  59.   fetchsamples()
Add Comment
Please, Sign In to add comment