If you assign to a variable anywhere in a function, that variable will be treated as a local variable everywhere in that function. So you would see the same error with the following code:
foo = 2
def test():
print foo
foo = 3
In other words, you cannot access the global or external variable if there is a local variable in the function of the same name.
To fix this, just give your local variable hmac
a different name:
def makereq(key, secret, path, data):
hash_data = path + chr(0) + data
secret = base64.b64decode(secret)
sha512 = hashlib.sha512
my_hmac = str(hmac.new(secret, hash_data, sha512))
header = {
'User-Agent': 'My-First-test',
'Rest-Key': key,
'Rest-Sign': base64.b64encode(my_hmac),
'Accept-encoding': 'GZIP',
'Content-Type': 'application/x-www-form-urlencoded'
}
return urllib2.Request(base + path, data, header)
Note that this behavior can be changed by using the global
or nonlocal
keywords, but it doesn’t seem like you would want to use those in your case.