import hmac, base64, hashlib, urllib2
base = 'https://.......'
def makereq(key, secret, path, data):
hash_data = path + chr(0) + data
secret = base64.b64decode(secret)
sha512 = hashlib.sha512
hmac = str(hmac.new(secret, hash_data, sha512))
header = {
'User-Agent': 'My-First-test',
'Rest-Key': key,
'Rest-Sign': base64.b64encode(hmac),
'Accept-encoding': 'GZIP',
'Content-Type': 'application/x-www-form-urlencoded'
}
return urllib2.Request(base + path, data, header)
错误: makereq中第8行的文件“C/Python27/btctest.py” hmac=str(hmac.new(secret,散列数据,sha512)) unbundlocalerror:赋值前引用的局部变量“hmac”
有人知道为什么吗?谢谢
您正在重新定义函数范围内的
hmac
变量,因此import
语句中的全局变量不在函数范围内。重命名函数scopehmac
变量应该可以解决您的问题。如果在函数中的任意位置分配变量,则该变量将被视为该函数中的局部变量everywhere。因此,您将看到与以下代码相同的错误:
换句话说,如果函数中存在同名的局部变量,则无法访问全局或外部变量。
要解决这个问题,只需给局部变量
hmac
一个不同的名称:注意,可以通过使用
global
或nonlocal
关键字来更改此行为,但似乎您不希望在您的案例中使用这些关键字。相关问题 更多 >
编程相关推荐