一点背景:我正在Windows10计算机上使用Python2.7.12。 这是迄今为止我在Python中遇到的最奇怪的问题之一。你知道吗
我编写了一个脚本,用正确的头向API发出GET请求,并获取一些XML数据。作为记录,当我将这样的脚本粘贴到python文件中并通过CMD运行它时,它工作得非常好。你知道吗
但是。。你知道吗
当我把它包装到一个函数中时,它就停止工作了。没有什么 否则,只需将其包装到函数中,并使用
if __name__ == '__main__':
my_new_function()
从CMD运行它,它将不再工作。它仍然工作,但是API说我有错误的身份验证凭证,因此我没有得到任何数据。你知道吗
我检查了这段代码中的每一段字符串,都是ASCII编码的。我还检查了时间戳,它们都是正确的。你知道吗
这是我的剧本:
SECRET_KEY = 'YYY'
PUBLIC_KEY = 'XXX'
content_type = 'application/xml'
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
method = 'GET'
uri = '/uri'
msg = """{method}
{content_type}
{date}
x-bol-date:{date}
{uri}""".format(content_type=content_type,
date=date,
method=method,
uri=uri)
h = hmac.new(
SECRET_KEY,
msg, hashlib.sha256)
b64 = base64.b64encode(h.digest())
signature = PUBLIC_KEY + b':' + b64
headers = {'Content-Type': content_type,
'X-BOL-Date': date,
'X-BOL-Authorization': signature}
r = requests.get('example.com/uri', headers=headers)
函数中的相同代码:
def get_orders():
SECRET_KEY = 'XXX'
PUBLIC_KEY = 'YYY'
content_type = 'application/xml'
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
method = 'GET'
uri = '/uri'
msg = """{method}
{content_type}
{date}
x-bol-date:{date}
{uri}""".format(content_type=content_type,
date=date,
method=method,
uri=uri)
h = hmac.new(
SECRET_KEY,
msg, hashlib.sha256)
b64 = base64.b64encode(h.digest())
signature = PUBLIC_KEY + b':' + b64
headers = {'Content-Type': content_type,
'X-BOL-Date': date,
'X-BOL-Authorization': signature}
r = requests.get('example.com/uri', headers=headers)
if __name__ == '__main__':
get_orders()
我认为多行字符串在函数中缩进时会有空格。将它连接到每一行,它应该可以工作。你知道吗
相关问题 更多 >
编程相关推荐