API 误解带有特殊字符的密码

问题描述 投票:0回答:1

我使用 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 格式返回。

我很难找出这一切的根源,想听听你对我的看法以及如何解决它的看法。

python authentication http-headers
1个回答
1
投票

试试这个:

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, you will need to use

.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))
© www.soinside.com 2019 - 2024. All rights reserved.