我使用 python 代码连接到 API 以检索 json 格式的信息。密码用于 API 的身份验证。到目前为止,身份验证工作正常,但由于我将密码更改为带有特殊字符的密码,所以出现了问题。我猜 API 或我使用的代码都没有很好地处理密码。
这是一段似乎导致错误的代码:
# Create connection and request header.
# This class does not perform any verification of the server`s certificate.
conn = HTTPSConnection(ADDRESS)
auth_header = 'Basic %s' % (':'.join([USER_NAME, PASSWORD]).encode('Base64').strip('\r\n'))
request_header = {'Authorization':auth_header.decode(),
'Content-Type': content_type}
执行代码后出现的错误如下:
response = self.perform_request(log, 'GET', 'network', params=query)
File "/usr/local/lib/python2.7/query_code.py", line 103, in perform_request
auth_header = 'Basic %s' % str(":".join([USER_NAME, PASSWORD]).encode('Base64').strip('\r\n'))
TypeError: sequence item 1: expected string or Unicode, NoneType found
我应该成功连接到 API,代码为 200,结果以 json 格式返回。
我很难找出这一切的根源,想听听您对我的看法以及如何解决它的看法。
最佳答案
试试这个:
def basic_token(key, secret):
return base64.b64encode(bytes(f'{key}:{secret}', 'utf-8')).decode('utf-8')
auth_header = f'basic {basic_token(USERNAME, PASSWORD)}'
如果您使用的是 python 版本 < 3.6,则需要使用 .format
而不是 f-strings
:
def basic_token(key, secret):
return base64.b64encode(bytes('{}:{}'.format(key, secret), 'utf-8')).decode('utf-8')
auth_header = 'basic {}'.format(basic_token(USERNAME, PASSWORD))
关于python - API 错误解释带有特殊字符的密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311469/