[英]Python script stops working when I put it inside a function
Little bit of background: I'm using Python 2.7.12 on a Windows 10 computer. 背景知识:我在Windows 10计算机上使用Python 2.7.12。 This is by far one of the oddest problems I have ever encountered with Python.
到目前为止,这是我用Python遇到过的最奇怪的问题之一。
I have written a script that makes a GET request to an API, with the correct headers, and gets some XML data back. 我编写了一个脚本,该脚本使用正确的标头向API发出GET请求,并获取一些XML数据。 For the record, when I paste the script like this in a python file and run it via CMD, it works perfectly fine.
作为记录,当我将这样的脚本粘贴到python文件中并通过CMD运行它时,它的运行情况非常好。
But.. 但..
It stops working as soon as I wrap this inside a function. 只要将其包装在函数中,它就会停止工作。 Nothing else, just wrap it inside a function, and use
没什么,只需将其包装在函数中,然后使用
if __name__ == '__main__':
my_new_function()
to run it from CMD and it won't work anymore. 从CMD运行它,它将不再起作用。 It still works but the API says I have wrong auth credentials, and thus I don't get any data back.
它仍然可以使用,但是API指出我的身份验证凭据错误,因此我没有获得任何数据。
I went over every piece of string that is in this code, and it's all ASCII encoded. 我遍历了这段代码中的所有字符串,并且所有字符串都是ASCII编码的。 I also checked the timestamps, and they are all correct.
我还检查了时间戳,它们都是正确的。
This is my script: 这是我的脚本:
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)
the same code inside a function: 函数内的相同代码:
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()
I think your multi-line string is getting spaces in it when you indent it in a function. 我认为当您在函数中缩进时,多行字符串在其中包含空格。 Concatenate it on each line instead and it should work.
而是在每行上串联它,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.