我正在Python中編寫一個OAuth腳本。OAuth與Python中的Twitter腳本不起作用
爲了測試這個,我使用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:未經授權)。
我引用this question,但失敗。
請給我一些建議。謝謝。
+1在Python示例中使用適當的示例字符串。 – 2010-02-11 13:18:03