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

yipeiwu_com6年前Python基础

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

代码如下:

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

调用样例:

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

输出

Basic YWRtaW46MTIzNDU2

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

相关文章

Python 实现域名解析为ip的方法

今天得了一批域名,需要把域名解析成ip 因为量比较大所以采用了多进程和队列的方式 from multiprocessing import Process,Queue,Pool imp...

Python实现HTTP协议下的文件下载方法总结

本文介绍了几种常用的python下载文件的方法,具体使用到了htttplib2,urllib等包,希望对大家有帮忙。 1.简单文件下载 使用htttplib2,具体代码如下: h =...

对python模块中多个类的用法详解

如下所示: import wuhan.wuhan11 class Han: def __init__(self, config): self.batch_size = co...

在Python的Django框架中为代码添加注释的方法

就像HTML或者Python,Django模板语言同样提供代码注释。 注释使用 {# #} : {# This is a comment #} 注释的内容不会在模板渲染时输出。...

Python split() 函数拆分字符串将字符串转化为列的方法

函数:split() Python中有split()和os.path.split()两个函数,具体作用如下: split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字...