【发布时间】:2017-04-09 08:59:59
【问题描述】:
一点背景知识:我在 Windows 10 计算机上使用 Python 2.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()
【问题讨论】:
-
向我们展示了在哪里以及如何将其包装在一个函数中。
-
我已经更新了答案
标签: python python-2.7 google-app-engine django-1.9