Python 3.4错误"必须在散列之前编码Unicode对象"

Sar*_*kar 9 python-3.x

使用oauth2从Twitter获取数据,但得到的错误为:

必须在散列之前对Unicode对象进行编码

使用下面的代码,

def oauth_req(url, key, secret, http_method="GET", post_body="",http_headers=None):
    consumer = oauth2.Consumer(key=API_KEY, secret=API_SECRET)
    token = oauth2.Token(key=key, secret=secret)
    client = oauth2.Client(consumer, token)
    resp, content = client.request(url, method=http_method, body=post_body, headers=http_headers)
    return content
data = oauth_req(url, TOKEN_KEY, TOKEN_SECRET)
Run Code Online (Sandbox Code Playgroud)

还尝试了我传递给def的变量的utf8编码值.

File "<pyshell#11>", line 1, in <module> 
    data = oauth_req(url, TOKEN_KEY, TOKEN_SECRET) 
File "<pyshell#8>", line 6, in oauth_req
    body=post_body, headers=http_headers) 
File "C:\Python35-32\lib\site-packages\oauth2_init_.py", line 673, in request 
    req.sign_request(self.method, self.consumer, self.token) 
File "C:\Python35-32\lib\site-packages\oauth2_init_.py", line 493, in sign_request 
    self['oauth_body_hash'] = base64.b64encode(sha1(self.body).digest()) 
TypeError: Unicode-objects must be encoded before hashing 
Run Code Online (Sandbox Code Playgroud)

Jam*_*s K 10

body参数client.request应该是一个bytestring.所以首先修复默认值

def oauth_req(url, key, secret, http_method="GET", post_body=b"", http_headers=None):
Run Code Online (Sandbox Code Playgroud)

(那应该修复示例代码中的错误)

然后确保为post-body传递给this函数的数据是一个bytestring,因为它的sha hash将被计算.要将字符串转换为字节,请使用mybytestring = bytes(mystring, "utf-8")或使用任何正确的编码.

以下是来源的相关行: