The Requests streaming example does not work in my environment

前端 未结 2 1909
说谎
说谎 2021-02-10 09:55

I\'ve been trying to consume the Twitter Streaming API using Python Requests.

There\'s a simple example in the documentation:

import requests
import jso         


        
相关标签:
2条回答
  • 2021-02-10 10:23

    Ah, I found the answer by reading the code. At some point, a prefetch parameter was added to the post method (and other methods, I assume).

    I just needed to add a prefetch=False kwarg to requests.post().

    0 讨论(0)
  • 2021-02-10 10:27

    You need to switch off prefetching, which I think is a parameter that changed defaults:

    r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
        data={'track': 'requests'}, auth=('username', 'password'),
        prefetch=False)
    
    for line in r.iter_lines():
        if line: # filter out keep-alive new lines
            print json.loads(line)
    

    Note that as of requests 1.x the parameter has been renamed, and now you use stream=True:

    r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
        data={'track': 'requests'}, auth=('username', 'password'),
        stream=True)
    
    for line in r.iter_lines():
        if line: # filter out keep-alive new lines
            print json.loads(line)
    
    0 讨论(0)
提交回复
热议问题