【问题标题】:Reddit API and voting. Not accepting modhash/cookie. .error.USER_REQUIREDReddit API 和投票。不接受 modhash/cookie。 .error.USER_REQUIRED
【发布时间】:2012-10-18 00:39:56
【问题描述】:

我正在尝试让投票 API 正常工作,但我收到错误 .error.USER_REQUIRED。不知道为什么,但我认为我必须以错误的方式发送 modhash 或会话 cookie,因为登录正常

我的代码如下所示:

UP = {'user': username, 'passwd': password, 'api_type': 'json',}

client = requests.session()

r = client.post('http://www.reddit.com/api/login', data=UP)

j = json.loads(r.text)

mymodhash = j['json']['data']['modhash']

url = 'http://www.reddit.com/api/vote/.json'
postdata = {'id': thing, 'dir': newdir, 'uh': mymodhash}
vote = client.post(url, data=json.dumps(newdata))

错误:

{"jquery": [[0, 1, "refresh", []], [0, 2, "attr", "find"], [2, 3, "call", [".error.USER_REQUIRED"]], [3, 4, "attr", "show"], [4, 5, "call", []], [5, 6, "attr", "text"], [6, 7, "call", ["please login to do that"]], [7, 8, "attr", "end"], [8, 9, "call", []]]}

【问题讨论】:

    标签: python api reddit


    【解决方案1】:

    要登录您应该发布到ssl.reddit.com,这样您就不会以纯文本形式发布您的凭据。另外,你应该设置一个用户代理。

    以下是对您的 /r/redditdev 提交进行投票的工作示例。

    import requests
    # Login                                                                                                
    client = requests.session(headers={'User-Agent': 'Requests test'})
    data = {'user': 'USERNAME', 'passwd': 'PASSWORD', 'api_type': 'json'}
    r = client.post('https://ssl.reddit.com/api/login', data=data)
    modhash = r.json['json']['data']['modhash']
    
    # Vote                                                                                                 
    data = {'id': 't3_11mr32', 'dir': '1', 'uh': modhash, 'api_type': 'json'}
    r = client.post('http://www.reddit.com/api/vote', data=data)
    print r.status_code  # Should be 200                                                                   
    print r.json  # Should be {}
    

    另外,除非你真的对 reddit 的 API 如何在幕后工作感兴趣,否则我建议你使用PRAW

    【讨论】:

    • 什么是“用户代理”:“请求测试”?
    • 这向 Reddit 表明您是标识为 Requests test 的客户。根据 Reddit 的 API,这个用户代理应该更具描述性:github.com/reddit/reddit/wiki/API#rules。还值得注意的是,Reddit 的 API 不再正式支持第三方客户端的 cookie-auth,因此您真的应该研究 OAuth。
    【解决方案2】:

    您可以将会话对象与with 语句一起使用。

    import requests
    
    UP = {'user': username, 'passwd': password, 'api_type': 'json'}
    url_prefix = "http://www.reddit.com"
    with requests.session() as client:
        client.post(url_prefix + '/login', data=UP)
    
        <...something else what you want...>
    

    【讨论】:

    • 我已经试过了,仍然不接受登录。我也尝试过从reddit.com/api/me.json 获取 modhash,但仍然拒绝。我想我一定误解了 modhash 的工作原理,也许它会因为我请求 URL 的方式而改变。也可能是我猜的 cookie。
    猜你喜欢
    • 2012-01-24
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2010-10-04
    • 2018-07-01
    相关资源
    最近更新 更多