【问题标题】:requests.get keeps hanging with Twitter Api (Python Requests library)requests.get 一直挂在 Twitter Api(Python 请求库)上
【发布时间】:2012-08-07 20:21:26
【问题描述】:

到目前为止我的代码:

import requests
import json

url = "https://stream.twitter.com/1/statuses/sample.json"

r = requests.get(url, auth = ('username', 'password'))
print r.status_code

当我在控制台中运行此脚本时,它一直挂起,但是当我运行等效的 urllib2 时,我得到了很好的响应:

from urllib2 import *

password_mgr = HTTPPasswordMgrWithDefaultRealm()
url = "https://stream.twitter.com/1/statuses/sample.json"
password_mgr.add_password(None, url, 'username', 'password')
h = HTTPBasicAuthHandler(password_mgr)
opener = build_opener(h)
page = opener.open(url)
print page.getcode()

这将返回200。有谁知道问题出在哪里?

编辑:另外,当我在上面的代码中调整密码时,我得到了适当的401 响应。我认为这是因为发生了一些阻塞?

【问题讨论】:

    标签: python json twitter python-requests


    【解决方案1】:

    我也遇到过这个问题,它只影响请求版本 > 0.13.5。 要解决此问题,请在 requests.get 调用中禁用预取:

    r = requests.get(url, auth = ('username', 'password'), prefetch=False)
    

    【讨论】:

    • 为什么这样可以解决问题?根据文档,预取已经默认为 False。
    【解决方案2】:

    不确定您是否可以按照您的方式调用 requests.get。如果传递参数,则需要包含字典。像这样?

    auth = {'username': 'username', 'password': 'password'}
    r = requests.get("https://stream.twitter.com/1/statuses/sample.json", params=auth)
    print r.status_code
    

    完整阅读此链接,了解使用 requests.get 的正确方法 http://docs.python-requests.org/en/latest/user/quickstart/

    【讨论】:

    • 编辑:没关系,它又给了我 401。我认为您必须在“auth”参数中传递用户名/密码组合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多