首页 > 解决方案 > API 错误解释带有特殊字符的密码

问题描述

我使用 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

我应该使用代码 200 成功连接到 API,并以 json 格式返回结果。

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

标签: pythonapiauthenticationheader

解决方案


试试这个:

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)}'

如果您使用的是 < 3.6 的 python 版本,则需要使用.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))

推荐阅读