经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
Python3.5内置模块之shelve模块、xml模块、configparser模块、hashlib、hmac模块用法分析
来源:jb51  时间:2019/4/28 8:43:04  对本文有异议

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

1、shelve模块

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

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

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

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4. import shelve
  5. import datetime
  6. d = shelve.open('shelve_test') # 打开一个文件
  7. info = {
  8. "age":23,
  9. "job":"IT"
  10. }
  11. name = ["alex", "rain", "test"]
  12. d["name"] = name # 持久化列表
  13. d["info"] = info # 持久化字典
  14. d["data"] = datetime.datetime.now()
  15. d.close()
  16.  

运行结果:产生3个文件

从shelve中数据读取:get方法

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

运行结果:

['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

  1. <?xml version="1.0"?>
  2. <data>
  3. <country name="Liechtenstein">
  4. <rank updated="yes">2</rank>
  5. <year>2008</year>
  6. <gdppc>141100</gdppc>
  7. <neighbor name="Austria" direction="E"/>
  8. <neighbor name="Switzerland" direction="W"/>
  9. </country>
  10. <country name="Singapore">
  11. <rank updated="yes">5</rank>
  12. <year>2011</year>
  13. <gdppc>59900</gdppc>
  14. <neighbor name="Malaysia" direction="N"/>
  15. </country>
  16. <country name="Panama">
  17. <rank updated="yes">69</rank>
  18. <year>2011</year>
  19. <gdppc>13600</gdppc>
  20. <neighbor name="Costa Rica" direction="W"/>
  21. <neighbor name="Colombia" direction="E"/>
  22. </country>
  23. </data>
  24.  

(2)Python中操作xml模块

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

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

运行结果:

<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,代码如下:

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

运行结果:

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

3、configparser模块

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

  1. [DEFAULT]
  2. ServerAliveInterval = 45
  3. Compression = yes
  4. CompressionLevel = 9
  5. ForwardX11 = yes
  6. [bitbucket.org]
  7. User = hg
  8. [topsecret.server.com]
  9. Port = 50022
  10. ForwardX11 = no
  11.  

Python生成配置文档:

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

4、hashlib模块

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

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

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4. import hashlib
  5. m = hashlib.md5() #生成对象
  6. m.update(b"Hello")
  7. m.update(b"It's me")
  8. print(m.digest())
  9. m.update(b"It's been a long time since last time we ...")
  10. print(m.digest()) #2进制格式hash
  11. print(len(m.hexdigest())) #16进制格式hash
  12. print(m.hexdigest())
  13. # ######## md5 ########
  14. hash = hashlib.md5()
  15. hash.update(b'admin')
  16. print("md5:",hash.hexdigest())
  17. # ######## sha1 ########
  18. hash = hashlib.sha1()
  19. hash.update(b'admin')
  20. print("sha1:",hash.hexdigest())
  21. # ######## sha256 ########
  22. hash = hashlib.sha256()
  23. hash.update(b'admin')
  24. print("sha256:",hash.hexdigest())
  25.  

运行结果:

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 + 消息明文再加密,

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

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

更多关于Python相关内容感兴趣的读者可查看jb51专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号