python - 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 格式返回结果。
我很难找出这一切的根源,想听听你对我的看法以及如何解决它的看法。
解决方案
试试这个:
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))
推荐阅读
- c++ - 当 std::string/char const* 已经在 utf-8 中时,从 std::string/char const* 创建 std::u8string
- python - 如何在 Django Rest Framework 中为外键显示字段值而不是 id,以确保所有字段都像以前一样在 DRF HTML 表单上显示
- mongodb - 电子邮件地址作为 _id 而不是 OID?
- ssl - 使用 ActiveMQ Artemis + TLS 进行 JMeter 测试
- php - 根据键合并数组数据
- python - For 和 while 函数,具有多个终止条件的重复结构
- database - FMX LiveBindings CustomFormat IfThen 具有三个或更多结果
- java - 如何在 Spring 或 EE 上重写 Guice Interface DI Injector.getInjector().getInstance(Interface.class)
- php - 抽象静态方法中的实例子类
- python - 尝试在 for 循环中使用列表索引