Python3.5内置模块之shelve模块、xml模块、configparser模块、hashlib、hmac模块用法分析


Posted in Python onApril 27, 2019

本文实例讲述了Python3.5内置模块之shelve模块、xml模块、configparser模块、hashlib、hmac模块用法。分享给大家供大家参考,具体如下:

1、shelve模块

shelve类似于一个key-value数据库,可以很方便的用来保存Python的内存对象,其内部使用pickle来序列化数据

简单来说,使用者可以将一个列表、字典、或者用户自定义的类实例保存到shelve中,下次需要用的时候直接取出来,

就是一个Python内存对象,不需要像传统数据库一样,先取出数据,然后用这些数据重新构造一遍所需要的对象。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import shelve
import datetime
d = shelve.open('shelve_test') # 打开一个文件
info = {
  "age":23,
  "job":"IT"
}
name = ["alex", "rain", "test"]
d["name"] = name # 持久化列表
d["info"] = info # 持久化字典
d["data"] = datetime.datetime.now()
d.close()

运行结果:产生3个文件

Python3.5内置模块之shelve模块、xml模块、configparser模块、hashlib、hmac模块用法分析

从shelve中数据读取:get方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import shelve
import datetime
d = shelve.open('shelve_test') # 打开一个文件
print(d.get("name"))
print(d.get("info"))
print(d.get("data"))

运行结果:

['alex', 'rain', 'test']
{'job': 'IT', 'age': 23}
2017-09-29 18:31:12.013709

2、xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,在json还没诞生时,

大家只能选择用xml,至今很多传统公司如金融行业的很多系统的接口还主要是xml。xml的格式如下,就是通过<>节点来区别数据结构的。

(1)xml文件示例代码如下:文件名为:xml_test.xml

<?xml version="1.0"?>
<data>
  <country name="Liechtenstein">
    <rank updated="yes">2</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor name="Austria" direction="E"/>
    <neighbor name="Switzerland" direction="W"/>
  </country>
  <country name="Singapore">
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
  <country name="Panama">
    <rank updated="yes">69</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor name="Costa Rica" direction="W"/>
    <neighbor name="Colombia" direction="E"/>
  </country>
</data>

(2)Python中操作xml模块

xml协议在各种语言里的都是支持的,在python中可以用以下模块操作xml 。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python中操作xml模块
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")  #要处理的xml文件名
root = tree.getroot()  #root是一个内存对象
print(root)
print(root.tag)    #打印标签名
#print(ET.parse("xml_test.xml").getroot().tag)
# 遍历xml文档
for child in root:
  print(child.tag, child.attrib)  #打印下一级的标签名和属性
  for i in child:
    print(i.tag,i.attrib,i.text)

Python3.5内置模块之shelve模块、xml模块、configparser模块、hashlib、hmac模块用法分析

运行结果:

<Element 'data' at 0x0062E8A0>
data
country {'name': 'Liechtenstein'}
rank {'updated': 'yes'} 2
year {} 2008
gdppc {} 141100
neighbor {'direction': 'E', 'name': 'Austria'} None
neighbor {'direction': 'W', 'name': 'Switzerland'} None
country {'name': 'Singapore'}
rank {'updated': 'yes'} 5
year {} 2011
gdppc {} 59900
neighbor {'direction': 'N', 'name': 'Malaysia'} None
country {'name': 'Panama'}
rank {'updated': 'yes'} 69
year {} 2011
gdppc {} 13600
neighbor {'direction': 'W', 'name': 'Costa Rica'} None
neighbor {'direction': 'E', 'name': 'Colombia'} None

只遍历节点year,代码如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python中操作xml模块
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")  #要处理的xml文件名
root = tree.getroot()  #root是一个内存对象
print(root)
print(root.tag)    #打印标签名
# 只遍历year 节点
for node in root.iter('year'):
  print(node.tag, node.text)

运行结果:

<Element 'data' at 0x0050E8D0>
data
year 2008
year 2011
year 2011

3、configparser模块

用于生成和修改常见配置文档,常见文档格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no

Python生成配置文档:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#python生成配置文档
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
  config.write(configfile)

4、hashlib模块

做一个映射关系,将字符串转成数字,用于加密相关的操作。

3.x里主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import hashlib
m = hashlib.md5()  #生成对象
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
m.update(b"It's been a long time since last time we ...")
print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
print(m.hexdigest())
# ######## md5 ########
hash = hashlib.md5()
hash.update(b'admin')
print("md5:",hash.hexdigest())
# ######## sha1 ########
hash = hashlib.sha1()
hash.update(b'admin')
print("sha1:",hash.hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash.update(b'admin')
print("sha256:",hash.hexdigest())

运行结果:

b']\xde\xb4{/\x92Z\xd0\xbf$\x9cR\xe3Br\x8a'
b'\xa0\xe9\x89E\x03\xcb\x9f\x1a\x14\xaa\x07?<\xae\xfa\xa5'
32
a0e9894503cb9f1a14aa073f3caefaa5
md5: 21232f297a57a5a743894a0e4a801fc3
sha1: d033e22ae348aeb5660fc2140aec35850c4da997
sha256: 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

5、hmac 模块

它内部对我们创建 key 和 内容 再进行处理然后再加密。

散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。

使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;一般用于网络通信中消息加密。

前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,

拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。

import hmac
h = hmac.new(b'zxc', 'cvb你好'.encode(encoding="utf-8"))
print(h.digest())
print(h.hexdigest())
#运行结果:
#b'\xc1\x89\t#VQ\xa4\x00\xbf\xed\xb2_\xc1s\xfa\xd2'
#c18909235651a400bfedb25fc173fad2

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python读取一个目录下所有目录和文件的方法
Jul 15 Python
python访问抓取网页常用命令总结
Apr 11 Python
Python基于回溯法子集树模板解决最佳作业调度问题示例
Sep 08 Python
python类的方法属性与方法属性的动态绑定代码详解
Dec 27 Python
Python 错误和异常代码详解
Jan 29 Python
python爬取m3u8连接的视频
Feb 28 Python
python中从str中提取元素到list以及将list转换为str的方法
Jun 26 Python
Laravel+Dingo/Api 自定义响应的实现
Feb 17 Python
python实现感知机线性分类模型示例代码
Jun 02 Python
150行Python代码实现带界面的数独游戏
Apr 04 Python
Opencv图像处理:如何判断图片里某个颜色值占的比例
Jun 03 Python
python thrift 实现 单端口多服务的过程
Jun 08 Python
python爬取基于m3u8协议的ts文件并合并
Apr 26 #Python
python游戏开发之视频转彩色字符动画
Apr 26 #Python
python接口自动化测试之接口数据依赖的实现方法
Apr 26 #Python
python使用参数对嵌套字典进行取值的方法
Apr 26 #Python
python将视频转换为全字符视频
Apr 26 #Python
使用Python创建简单的HTTP服务器的方法步骤
Apr 26 #Python
Python3.5内置模块之random模块用法实例分析
Apr 26 #Python
You might like
php图片验证码代码
2008/03/27 PHP
php出现Cannot modify header information问题的解决方法大全
2008/04/09 PHP
PHP实现的购物车类实例
2015/06/17 PHP
JavaScript toFixed() 方法
2010/04/15 Javascript
javascript面向对象编程(一) 实例代码
2010/06/25 Javascript
在Ajax中使用Flash实现跨域数据读取的实现方法
2010/12/02 Javascript
用jQuery实现的智能隐藏、滑动效果的返回顶部代码
2014/03/18 Javascript
Javascript中使用parseInt函数需要注意的问题
2015/04/02 Javascript
在Ubuntu系统上安装Node.JS的教程
2015/10/15 Javascript
JS判断图片是否加载完成方法汇总(最新版)
2016/05/13 Javascript
浅谈JS原生Ajax,GET和POST
2016/06/08 Javascript
require简单实现单页应用程序(SPA)
2016/07/12 Javascript
Javascript实现代码折叠功能
2016/08/25 Javascript
微信小程序教程之本地图片上传(leancloud)实例详解
2016/11/16 Javascript
详解Vue.js中.native修饰符
2018/04/24 Javascript
深入理解Vue父子组件生命周期执行顺序及钩子函数
2018/08/12 Javascript
node.js命令行教程图文详解
2019/05/27 Javascript
vue项目实现图片上传功能
2019/12/23 Javascript
vue实现微信浏览器左上角返回按钮拦截功能
2020/01/18 Javascript
在vue中使用image-webpack-loader实例
2020/11/12 Javascript
浅析python中SQLAlchemy排序的一个坑
2017/02/24 Python
Python基于QRCode实现生成二维码的方法【下载,安装,调用等】
2017/07/11 Python
Python调用C# Com dll组件实战教程
2017/10/12 Python
详解python中的Turtle函数库
2018/11/19 Python
Python读取excel指定列生成指定sql脚本的方法
2018/11/28 Python
Python Sphinx使用实例及问题解决
2020/01/17 Python
如何在Python3中使用telnetlib模块连接网络设备
2020/09/21 Python
python 线程的五个状态
2020/09/22 Python
美国糖果店:Sugarfina
2019/02/21 全球购物
地球鞋加拿大官网:Earth Shoes Canada
2020/11/17 全球购物
社区食品安全实施方案
2014/03/28 职场文书
爱国演讲稿400字
2014/05/07 职场文书
设备管理实施方案
2014/05/31 职场文书
文体活动总结
2015/02/04 职场文书
2015年社区居委会工作总结
2015/05/18 职场文书
Oracle锁表解决方法的详细记录
2022/06/05 Oracle