python - API 错误解释带有特殊字符的密码

标签 python api authentication header

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

相关文章:

python - pandas 中是否有函数语法用于根据整数位置设置系列值?

python - 错误 : torch is not a supported wheel on this platform (Linux, 非 conda )

javascript - 如何使用 JavaScript 检测网页中的登录表单?

python - 如何在Python中正确使用断言?

python - SQL Server DATE 作为字符串检索到 pandas

android - org.json.JSONException : Value &lt;! java.lang.String 类型的 DOCTYPE 无法转换为 JSONObject

api - 谷歌博客搜索 API 的替代 API

javascript - Django 并在不同的 View 中向外部 API 发布请求

asp.net-mvc - ASP.Net MVC 中仅允许匿名的属性

mysql - 通过 Laravel 存储第 3 方数据库/API 凭证的安全方式