Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Twitter Stream API with Python

Thank you in advanced! I deleted my OAuth information and this code worked for the non-streaming component of the Twitter API. I know want a continuous session and I am not doing that. How do I create one? I am using Python 3.3.2 and would prefer not to use a library like tweepy.

import requests
import json
import time
from requests_oauthlib import OAuth1Session

twitter = OAuth1Session('',client_secret='',resource_owner_key='',resource_owner_secret='')


url = 'https://userstream.twitter.com/1.1/user.json'
r = twitter.get(url)
data = json.loads(r.text)
print(data)
like image 818
user3159139 Avatar asked Mar 13 '26 12:03

user3159139


1 Answers

As you can see in the OAuth1Session sourcecode, the class inherits from requests.Session.

You can use twitter.get(url, stream=True), as described in the official requests streaming example.

The return value of twitter.get(...) then exposes a generator interface, so you can iterate over the lines. Note, however, that you manually have to separate the JSON records in the stream and pass them to json.loads() one-by-one.

like image 167
Uli Köhler Avatar answered Mar 15 '26 02:03

Uli Köhler