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使用marshal模块序列化实例

本文实例讲述了python使用marshal模块序列化的方法,分享给大家供大家参考。具体方法如下: 先来看看下面这段代码: import marshal data1 = ['abc'...

Python获取昨天、今天、明天开始、结束时间戳的方法

如下所示: #!/usr/bin/python # coding=utf-8 # import time import datetime # 今天日期 today = datetim...

Pycharm在创建py文件时,自动添加文件头注释的实例

Pycharm在创建py文件时,自动添加文件头注释的实例

1.选择File -> Settings 2.选择 File and Code Templates -> Files -> Python Script 编辑代码的样式...

python实现udp数据报传输的方法

本文实例讲述了Python实现UDP数据报传输的方法,非常具有实用价值。分享给大家供大家参考。具体方法分析如下: 服务端代码: import socket port = 8081...

利用ImageAI库只需几行python代码实现目标检测

利用ImageAI库只需几行python代码实现目标检测

什么是目标检测 目标检测关注图像中特定的物体目标,需要同时解决解决定位(localization) + 识别(Recognition)。相比分类,检测给出的是对图片前景和背景的理解,我们...