user3159139
user3159139

Reputation: 31

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)

Upvotes: 3

Views: 2263

Answers (1)

Uli Köhler
Uli Köhler

Reputation: 13750

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.

Upvotes: 1

Related Questions