Python:将 Base64 编码为 Basic 连接到 API [英] Python: Encode Base64 to Basic connect to an API

查看:39
本文介绍了Python:将 Base64 编码为 Basic 连接到 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到 API,我必须将用户名和密码编码为 64.授权"值应如下所示:Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ

当我尝试连接时,出现错误:未经授权:凭据错误".支持人员说我的凭据没问题,但他们对解决我的问题的反应很慢.

我怀疑代码的编码部分,但我不确定.你能看看我的代码并告诉我它可能有什么问题吗?

文档中有关身份验证部分的直接链接:http://developer.outbrain.com/home-page/amplify-api/documentation/#/reference/authentications/via-api

m = str(base64.b64encode(b'xxxxx:xxxxxxx'))标题 = {'授权':'基本' + m + ''}r = requests.get('https://api.outbrain.com/amplify/v0.1/login', headers=headers)打印(r.json())

解决方案

你需要使用 decode 从字节序列中正确获取一个字符串:

错误(注意结果中的 'b' 前缀和单引号):

<预><代码>>>>str(base64.b64encode(b'test'))"b'dGVzdA=='"

对:

<预><代码>>>>base64.b64encode(b'test').decode('utf-8')'dGVzdA=='

此外,requests 可以为您做到这一点:

from requests.auth import HTTPBasicAuthr = requests.get('https://api.outbrain.com/amplify/v0.1/login', auth=HTTPBasicAuth('user', 'pass'))

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?

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())

解决方案

You need to use decode to correctly get a string from the byte sequence:

Wrong (note the 'b' prefix and single quotes in the result):

>>> str(base64.b64encode(b'test'))
"b'dGVzdA=='"

Right:

>>> base64.b64encode(b'test').decode('utf-8')
'dGVzdA=='

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆