Python:将Base64编码为Basic连接到API [英] Python: Encode Base64 to Basic connect to an API
问题描述
我正在尝试连接到API,并且必须对用户名和密码进行编码64. 授权"值应如下所示:基本QWxhZGRpbjpvcGVuIHNlc2FtZQ
I'm trying to connect to an API and I've to encode64 the username and password. The 'Authorisation' value should look like this: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ
当我尝试连接时,出现错误:未授权:错误的凭据".支持人员说我的凭据还可以,但是响应速度很慢,无法解决我的问题.
When I try to connect I get an error: 'Unauthorized: Bad credentials'. The support says that my credentials are ok, but they are slow to respond to solve my issue.
我怀疑代码的编码部分,但不确定.您能看一下我的代码,然后告诉我它可能有什么问题吗?
I suspect the encoding part of the code, but I'm not sure. Could you please take a look at my code and tell me what could be wrong with it?
直接链接到文档中有关身份验证的部分: http://developer.outbrain. com/home-page/amplify-api/documentation/#/reference/authentications/via-api
The direct link to the section about authentication in the documentation : http://developer.outbrain.com/home-page/amplify-api/documentation/#/reference/authentications/via-api
m = str(base64.b64encode(b'xxxxx:xxxxxxx'))
headers = {
'Authorization': 'Basic ' + m + ''
}
r = requests.get('https://api.outbrain.com/amplify/v0.1/login', headers=headers)
print(r.json())
推荐答案
您需要使用decode
从字节序列中正确获取字符串:
You need to use decode
to correctly get a string from the byte sequence:
错误(请注意结果中的'b'前缀和单引号)
Wrong (note the 'b' prefix and single quotes in the result):
>>> str(base64.b64encode(b'test'))
"b'dGVzdA=='"
右:
>>> base64.b64encode(b'test').decode('utf-8')
'dGVzdA=='
此外,requests
可以为您执行此操作:
Additionally, requests
can do this for you:
from requests.auth import HTTPBasicAuth
r = requests.get('https://api.outbrain.com/amplify/v0.1/login', auth=HTTPBasicAuth('user', 'pass'))
这篇关于Python:将Base64编码为Basic连接到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!