Python 编码Basic Auth使用方法简单实例

时间:2022-09-24 11:48:00

本片博文主要介绍在Python3 环境下把用户名密码编码成字符串。

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
import base64
def get_basic_auth_str(username, password):
  temp_str = username + ':' + password
  # 转成bytes string
  bytesString = temp_str.encode(encoding="utf-8")
  # base64 编码
  encodestr = base64.b64encode(bytesString)
  # 解码
  decodestr = base64.b64decode(encodestr)
 
  return 'Basic ' + encodestr.decode()

调用样例:

?
1
print(get_basic_auth_str('admin', '123456'))

输出

?
1
Basic YWRtaW46MTIzNDU2

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/huplion/article/details/53177227