簡體   English   中英

使用Python中的Twitter腳本的OAuth不起作用

[英]OAuth with Twitter script in Python is not working

我正在用Python編寫OAuth腳本。

為了測試這個,我使用Twitter API。 但它運作不佳。

def test():
    params = {
            "oauth_consumer_key": TWITTER_OAUTH_CONSUMER_KEY,
            "oauth_nonce": "".join(random.choice(string.digits + string.letters) for i in xrange(7)),
            "oauth_signature_method": "HMAC-SHA1",
            "oauth_timestamp": str(int(time.time())),
            "oauth_token": res_dict["oauth_token"],
            "oauth_version": "1.0",
            }
    status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")}
    print status
    params.update(status)
    url = "http://twitter.com/statuses/update.xml"
    key = "&".join([TWITTER_OAUTH_CONSUMER_SECRET, res_dict["oauth_token_secret"]])
    msg = "&".join(["POST", urllib.quote(url,""),
                    urllib.quote("&".join([k+"="+params[k] for k in sorted(params)]), "-._~")])
    print msg
    signature = hmac.new(key, msg, hashlib.sha1).digest().encode("base64").strip()
    params["oauth_signature"] = signature
    req = urllib2.Request(url,
          headers={"Authorization":"OAuth", "Content-type":"application/x-www-form-urlencoded"})
    req.add_data("&".join([k+"="+urllib.quote(params[k], "-._~") for k in params]))
    print req.get_data()
    res = urllib2.urlopen(req).read()
    print res

此腳本(status =“Always_look_on_the_bright_side_of_life”)正在運行。

但是,如果狀態是“總是看着生活的光明面”(用空格替換下划線),它就不起作用(正在返回HTTP錯誤401:未經授權)。

我引用了這個問題 ,但失敗了。

請給我一些建議。 謝謝。

我剛剛在使用FaceBook的OAuth中遇到了同樣的問題。 問題是服務器端的簽名驗證失敗。 在此處查看您的簽名生成代碼:

msg = "&".join(["POST", urllib.quote(url,""),
                urllib.quote("&".join([k+"="+params[k] for k in sorted(params)]), "-._~")])
print msg
signature = hmac.new(key, msg, hashlib.sha1).digest().encode("base64").strip()

它使用字符串的原始(非編碼)形式來生成簽名。 但是,服務器端生成針對URL引用字符串驗證簽名:

req.add_data("&".join([k+"="+urllib.quote(params[k], "-._~") for k in params]))

要修復代碼,您需要通過從url encoded參數創建簽名來修復此行:

msg = "&".join(["POST", urllib.quote(url,""),
                urllib.quote("&".join([k+"="+urllib.quote(params[k], "-._~") for k in sorted(params)]), "-._~")])

解決此問題的最簡單方法是在status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")}之后添加status = urllib.quote(status) status = {"status": u"Always_look_on_the_bright_side_of_life".encode("UTF-8")} 這將根據需要轉義空格和其他特殊字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM