繁体   English   中英

从python中的base64编码字符串中获取字符串

[英]Get string from a base64 encoded string in python

我必须在python中发布到其他服务器。 在标头身份验证中,我必须包括一个base64编码的字符串。

我用base64模块来做:

import base64
#node here is '3180' but I also tried with text
node = base64.b64encode(node.encode('utf-8'))
node = 'Basic ' + str(node)
headers = {'Content-type': 'application/json', 'Authentication': node}
print(headers)

我得到的是:

{'Authentication': "Basic b'MzE4MA=='", 'Content-type': 'application/json'}

其中将b' ... '添加到节点base64字符串中。 有没有办法避免这些字符出现? 我不知道它们是否只是出现在打印件中或也已发送到服务器。

b64encode返回bytes而不是str 当您在不指定编码的情况下对其调用str()时,它实际上是在给您字节对象的Python表示形式b'MzE4MA==' ,而不是转换值。

为了避免这种情况,请使用node = 'Basic ' + node.decode('ascii')

请注意,您也可以使用str(node, encoding='ascii')但这会更长。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM