序列化 ,hashlib ,configparser ,logging ,collections模块

# 实例化  归一化 初始化 序列化    # 列表 元组 字符串# 字符串# .......得到一个字符串的结果 过程就叫序列化# 字典 / 列表 / 数字 /对象 -序列化->字符串# 为什么要序列化    # 1.要把内容写入文件 序列化    # 2.网络传输数据     序列化# 字符串-反序列化->字典 / 列表 / 数字 /对象

# 方法# dic = {‘k‘:‘v‘}# str_dic = str(dic)# print(dict(str_dic))# print([eval(str_dic)])# eval不能随便用

# jsonimport json# 只提供四个方法# dic = {‘aaa‘:‘bbb‘,‘ccc‘:‘ddd‘}# str_dic = json.dumps(dic)# print(dic)# print(str_dic,type(str_dic))# with open(‘json_dump‘,‘w‘) as f:#     f.write(str_dic)# ret = json.loads(str_dic)# print(ret,type(ret))# print(ret[‘aaa‘])

# dic = {‘aaa‘:‘bbb‘,‘ccc‘:‘ddd‘}# with open(‘json_dump2‘,‘w‘) as f:#     json.dump(dic,f)

# with open(‘json_dump2‘) as f:#     print(type(json.load(f)))
import json# json格式的限制1,json格式的key必须是字符串数据类型# json格式中的字符串只能是""

# 如果是数字为key,那么dump之后会强行转成字符串数据类型# dic = {1:2,3:4}# str_dic = json.dumps(dic)# print(str_dic)# new_dic = json.loads(str_dic)# print(new_dic)

# json是否支持元组,对元组做value的字典会把元组强制转换成列表# dic = {‘abc‘:(1,2,3)}# str_dic = json.dumps(dic)# print(str_dic)# new_dic = json.loads(str_dic)# print(new_dic)

# json是否支持元组做key,不支持# dic = {(1,2,3):‘abc‘}# str_dic = json.dumps(dic)  # 报错

# 对列表的dump# lst = [‘aaa‘,123,‘bbb‘,12.456]# with open(‘json_demo‘,‘w‘) as f:#     json.dump(lst,f)# with open(‘json_demo‘) as f:#     ret = json.load(f)#     print(ret)

# 能不能多次dump数据到文件里,可以多次dump但是不能load出来了# dic = {‘abc‘:(1,2,3)}# lst = [‘aaa‘,123,‘bbb‘,12.456]# with open(‘json_demo‘,‘w‘) as f:#     json.dump(lst,f)#     json.dump(dic,f)# with open(‘json_demo‘) as f:#     ret = json.load(f)#     print(ret)

# 想dump多个数据进入文件,用dumps# dic = {‘abc‘:(1,2,3)}# lst = [‘aaa‘,123,‘bbb‘,12.456]# with open(‘json_demo‘,‘w‘) as f:#     str_lst = json.dumps(lst)#     str_dic = json.dumps(dic)#     f.write(str_lst+‘\n‘)#     f.write(str_dic+‘\n‘)

# with open(‘json_demo‘) as f:#     for line in f:#         ret = json.loads(line)#         print(ret)

# 中文格式的 ensure_ascii = False# dic = {‘abc‘:(1,2,3),‘country‘:‘中国‘}# ret = json.dumps(dic,ensure_ascii = False)# print(ret)# dic_new = json.loads(ret)# print(dic_new)

# with open(‘json_demo‘,‘w‘,encoding=‘utf-8‘) as f:#     json.dump(dic,f,ensure_ascii=False)

# json的其他参数,是为了用户看的更方便,但是会相对浪费存储空间# import json# data = {‘username‘:[‘李华‘,‘二愣子‘],‘sex‘:‘male‘,‘age‘:16}# json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators=(‘,‘,‘:‘),ensure_ascii=False)# print(json_dic2)

# set不能被dump/dumps

********************************************************************************************
import  pickle# dump的结果是bytes,dump用的f文件句柄需要以wb的形式打开,load所用的f是‘rb‘模式# 支持几乎所有对象的序列化# 对于对象的序列化需要这个对象对应的类在内存中# 对于多次dump/load的操作做了良好的处理

# pic_dic = pickle.dumps(dic)# print(pic_dic)    # bytes类型# new_dic = pickle.loads(pic_dic)# print(new_dic)

# pickle支持几乎所有对象的# class Student:#     def __init__(self,name,age):#         self.name = name#         self.age = age## alex = Student(‘alex‘,83)# ret = pickle.dumps(alex)# 小花 = pickle.loads(ret)# print(小花.name)# print(小花.age)

# class Student:#     def __init__(self,name,age):#         self.name = name#         self.age = age## alex = Student(‘alex‘,83)# with open(‘pickle_demo‘,‘wb‘) as f:#     pickle.dump(alex,f)# with open(‘pickle_demo‘,‘rb‘) as f:#     旺财 = pickle.load(f)#     print(旺财.name)

# 学员选课系统  pickle模块来存储每个学员的对象

# with open(‘pickle_demo‘,‘wb‘) as f:#     pickle.dump({‘k1‘:‘v1‘}, f)#     pickle.dump({‘k11‘:‘v1‘}, f)#     pickle.dump({‘k11‘:‘v1‘}, f)#     pickle.dump({‘k12‘:[1,2,3]}, f)#     pickle.dump([‘k1‘,‘v1‘,‘l1‘], f)

# with open(‘pickle_demo‘,‘rb‘) as f:#     while True:#         try:#             print(pickle.load(f))#         except EOFError:#             break
******************************************************************************************** 
import shelvef = shelve.open(‘shelve_demo‘)f[‘key‘] = {‘k1‘:(1,2,3),‘k2‘:‘v2‘}f.close()

# f = shelve.open(‘shelve_demo‘)# content = f[‘key‘]# f.close()# print(content)

# shelve  如果你写定了一个文件# 改动的比较少# 读文件的操作比较多# 且你大部分的读取都需要基于某个key获得某个value
********************************************************************************************  

# 摘要算法的模块import hashlib# 能够把 一个 字符串 数据类型的变量# 转换成一个 定长的 密文的 字符串,字符串里的每一个字符都是一个十六进制数字

# 对于同一个字符串,不管这个字符串有多长,只要是相同的,# 无论在任何环境下,多少次执行,在任何语言中# 使用相同的算法\相同的手段得到的结果永远是相同的# 只要不是相同的字符串,得到的结果一定不同

# 登录的密文验证# ‘alex3714‘  # -> ‘127649364964908724afd‘

# 字符串 --> 密文# 密文 不可逆的 字符串

# 1234567 - > ‘127649364964908724afd‘# 算法 : 对于同一个字符串,用相同的算法,相同的手段去进行摘要,获得的值总是相同的# 1234567 - > ‘127649364964908724afd‘

# s1 = ‘alex3714‘  # aee949757a2e698417463d47acac93df# s2 = ‘alex3714qwghkdblkasjbvkhoufyowhdjlbvjnjxc‘  # d2d087c10aeba8276b21f8697ad3e810# md5是一个算法,32位的字符串,每个字符都是一个十六进制# md5算法 效率快 算法相对简单# md5_obj = hashlib.md5()# md5_obj.update(s1.encode(‘utf-8‘))# res = md5_obj.hexdigest()# print(res,len(res),type(res))

# 数据库 - 撞库# 111111 --> 结果# 666666# 123456# alex3714 --> aee949757a2e698417463d47acac93df

# s1 = ‘123456‘# md5_obj = hashli b.md5()# md5_obj.update(s1.encode(‘utf-8‘))# res = md5_obj.hexdigest()# print(res,len(res),type(res))

# 加盐  # alex3714  d3cefe8cdd566977ec41566f1f11abd9# md5_obj = hashlib.md5(‘任意的字符串作为盐‘.encode(‘utf-8‘))# md5_obj.update(s1.encode(‘utf-8‘))# res = md5_obj.hexdigest()# print(res,len(res),type(res))

# 恶意用户 注册500个账号# 张三|123456  ‘任意的字符串作为盐‘.encode(‘utf-8‘) d3cefe8cdd566977ec41566f1f11abd8# 李四|111111

# 动态加盐# username = input(‘username : ‘)# passwd = input(‘password : ‘)# md5obj = hashlib.md5(username.encode(‘utf-8‘))# md5obj.update(passwd.encode(‘utf-8‘))# print(md5obj.hexdigest())# ee838c58e5bb3c9e687065edd0ec454f

# sha1也是一个算法,40位的字符串,每个字符都是一个十六进制# 算法相对复杂 计算速度也慢# md5_obj = hashlib.sha1()# md5_obj.update(s1.encode(‘utf-8‘))# res = md5_obj.hexdigest()# print(res,len(res),type(res))

# 文件的一致性校验# md5_obj = hashlib.md5()# with open(‘5.序列化模块_shelve.py‘,‘rb‘) as f:#     md5_obj.update(f.read())#     ret1 = md5_obj.hexdigest()## md5_obj = hashlib.md5()# with open(‘5.序列化模块_shelve.py.bak‘,‘rb‘) as f:#     md5_obj.update(f.read())#     ret2 = md5_obj.hexdigest()# print(ret1,ret2)

# 如果这个文件特别大,内存装不下# 8g 10g# 按行读  文本 视频 音乐 图片 bytes# 按字节读 23724873 10240

# md5_obj = hashlib.md5()# md5_obj.update(‘hello,alex,sb‘.encode(‘utf-8‘))# print(md5_obj.hexdigest())

# md5_obj = hashlib.md5()# md5_obj.update(‘hello,‘.encode(‘utf-8‘))# md5_obj.update(‘alex,‘.encode(‘utf-8‘))# md5_obj.update(‘sb‘.encode(‘utf-8‘))# print(md5_obj.hexdigest())

# 大文件的已执行校验

md5_obj = hashlib.md5()with open(‘5.序列化模块_shelve.py.bak‘,‘rb‘) as f:    md5_obj.update(f.read())    # 循环 循环的读取文件内容    # 循环的来updateprint(md5_obj.hexdigest())********************************************************************************************

import configparser# file类型# f = open(‘setting‘)

# 有一种固定格式的配置文件# 有一个对应的模块去帮你做这个文件的字符串处理

# settings.py 配置

# import configparser## config = configparser.ConfigParser()## config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,#                       ‘Compression‘: ‘yes‘,#                      ‘CompressionLevel‘: ‘9‘,#                      ‘ForwardX11‘:‘yes‘#                      }## config[‘bitbucket.org‘] = {‘User‘:‘hg‘}## config[‘topsecret.server.com‘] = {‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘}## with open(‘example.ini‘, ‘w‘) as f:#    config.write(f)

import configparser

config = configparser.ConfigParser()# print(config.sections())        #  []config.read(‘example.ini‘)# print(config.sections())        #   [‘bitbucket.org‘, ‘topsecret.server.com‘]# print(‘bytebong.com‘ in config) # False# print(‘bitbucket.org‘ in config) # True# print(config[‘bitbucket.org‘]["user"])  # hg# print(config[‘DEFAULT‘][‘Compression‘]) #yes# print(config[‘topsecret.server.com‘][‘ForwardX11‘])  #no# print(config[‘bitbucket.org‘])          #<Section: bitbucket.org># for key in config[‘bitbucket.org‘]:     # 注意,有default会默认default的键#     print(key)# print(config.options(‘bitbucket.org‘))  # 同for循环,找到‘bitbucket.org‘下所有键# print(config.items(‘bitbucket.org‘))    #找到‘bitbucket.org‘下所有键值对# print(config.get(‘bitbucket.org‘,‘compression‘)) # yes get方法Section下的key对应的value
********************************************************************************************import logging
# 功能    # 1. 日志格式的规范    # 2. 操作的简化    # 3. 日志的分级管理

# logging不能帮你做的事情    # 自动生成你要打印的内容# 需要程序员自己在开发的时候定义好 :    # 在哪些地方需要打印,要打印的内容是什么,内容的级别

# logging模块的使用 :    # 普通配置型 简单的 可定制化差    # 对象配置型 复杂的 可定制化强

# 认识日志分级

# import logging# logging.debug(‘debug message‘)      # 调试模式# logging.info(‘info message‘)        # 基础信息# logging.warning(‘warning message‘)  # 警告# logging.error(‘error message‘)      # 错误# logging.critical(‘critical message‘)# 严重错误

# import logging# logging.basicConfig(level=logging.DEBUG)# logging.debug(‘debug message‘)      # 调试模式# logging.info(‘info message‘)        # 基础信息# logging.warning(‘warning message‘)  # 警告# logging.error(‘error message‘)      # 错误# logging.critical(‘critical message‘)# 严重错误

# import logging# logging.basicConfig(level=logging.DEBUG,#                     format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,#                     datefmt=‘%a, %d %b %Y %H:%M:%S‘,#                     filename=‘test.log‘)# logging.debug(‘debug message‘)      # 调试模式# logging.info(‘info message‘)        # 基础信息# logging.warning(‘warning message‘)  # 警告# logging.error(‘error message‘)      # 错误# logging.critical(‘critical message‘)# 严重错误

# basicConfig# 不能将一个log信息既输出到屏幕 又输出到文件

# logger对象的形式来操作日志文件

# 创建一个logger对象# 创建一个文件管理操作符# 创建一个屏幕管理操作符# 创建一个日志输出的格式

# 文件管理操作符 绑定一个 格式# 屏幕管理操作符 绑定一个 格式

# logger对象 绑定 文件管理操作符# logger对象 绑定 屏幕管理操作符

# import logging# # 创建一个logger对象# logger = logging.getLogger()# # 创建一个文件管理操作符# fh = logging.FileHandler(‘logger.log‘,encoding=‘utf-8‘)# # 创建一个屏幕管理操作符# sh = logging.StreamHandler()# # 创建一个日志输出的格式# format1 = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)# # # 文件管理操作符 绑定一个 格式# fh.setFormatter(format1)# # 屏幕管理操作符 绑定一个 格式# sh.setFormatter(format1)# logger.setLevel(logging.DEBUG)# # logger对象 绑定 文件管理操作符# logger.addHandler(fh)# # logger对象 绑定 屏幕管理操作符# logger.addHandler(sh)# # logger.debug(‘debug message‘)      # 调试模式# logger.info(‘我的信息‘)        # 基础信息# logger.warning(‘warning message‘)  # 警告# logger.error(‘error message‘)      # 错误# logger.critical(‘critical message‘)# 严重错误

import logginga=logging.getLogger()fh=logging.FileHandler(‘a1‘,encoding=‘utf-8‘)sh=logging.StreamHandler()

format1=logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)fh.setFormatter(format1)sh.setFormatter(format1)

a.setLevel(logging.DEBUG)

a.addHandler(fh)a.addHandler(sh)

a.debug(‘debug message‘)      # 调试模式a.info(‘我的信息‘)        # 基础信息a.warning(‘warning message‘)  # 警告a.error(‘error message‘)      # 错误a.critical(‘critical message‘)# 严重错误

input("")import logginglogging.basicConfig(level=logging.DEBUG,   #修改 DEBUG,INFO                    format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,                    datefmt=‘%a, %d %b %Y %H:%M:%S‘)exp = 3+4/4logging.debug(str(4/4))print(4)********************************************************************************************

# collections模块# 数据类型的扩展模块

# 什么是队列# 先进先出# import queue# q = queue.Queue()# print(q.qsize())# q.put(1)# q.put(‘a‘)# q.put((1,2,3))# q.put(({‘k‘:‘v‘}))# print(q.qsize())# print(‘q : ‘,q)# print(‘get : ‘,q.get())# print(q.qsize())

# deque 双端队列# from collections import deque# dq = deque()# dq.append(2)# dq.append(5)# dq.appendleft(‘a‘)# dq.appendleft(‘b‘)# print(dq)# # print(dq.pop())# # print(dq)# # print(dq.popleft())# # print(dq)# print(dq.remove(‘a‘))# print(dq.insert(2,‘123‘))# print(dq)

# 总结# 在insert remove的时候 deque的平均效率要高于列表# 列表根据索引查看某个值的效率要高于deque# append 和pop对于列表的效率是没有影响


原文地址:https://www.cnblogs.com/xdlzs/p/9461822.html

时间: 2024-07-31 02:37:04

序列化 ,hashlib ,configparser ,logging ,collections模块的相关文章

hashlib,configparser,logging模块

一.常用模块二 hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示). 注意:摘要算法不是一个解密算法.(摘要算法,检测一个字符串是否发生了变化) 应涂:1.做文件校验 2.登录密码 密码不能解密,但可以撞库,用'加盐'的方法就可以解决撞库的问题.所有以后设置密码的时候要设置的复杂一点. 1 import hashlib 2

常用模块(hashlib,configparser,logging)

hashlib hashlib 摘要算法的模块md5 sha1 sha256 sha512摘要的过程 不可逆能做的事:文件的一致性检测用户的加密认证 单纯的md5不够安全 加盐处理 简单的盐可能被破解 且破解之后所有的盐都失效 动态加盐 md5 = hashlib.md5() # 选择摘要算法中的md5类进行实例化,得到md5_obj md5.update(b'how to use md5 in python hashlib?') # 对一个字符串进行摘要 print(md5.hexdigest

python全栈开发【第十一篇】Python常用模块三(hashlib,configparser,logging)

hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示). 注意:摘要算法不是一个解密算法.(摘要算法,检测一个字符串是否发生了变化) 应涂:1.做文件校验 2.登录密码 密码不能解密,但可以撞库,用'加盐'的方法就可以解决撞库的问题.所有以后设置密码的时候要设置的复杂一点. #用户密码 import hashlib # md5

8.模块介绍 time &amp;datetime模块 random os sys shutil json &amp; picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式

本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.p

python 常用模块 time random os模块 sys模块 json &amp; pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess logging re正则 转自老男孩老师Yuan:http://www.cnblogs.com/yuanchenqi/articles/5732581.html 模块&包(* * * * *) 模块(modue)的概念: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,

logging模块,collections模块,random模块

logging日志模块 低配版 import logging logging.basicConfig(lexel=logging.INFO, format='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)s%(message)s filename='low版logging.log' ) logging.debug('debug message') logging.info('info message') logging.warning('

Python之常用模块(五)hashlib模块与collections模块

5.8 hashlib模块 hashlib模块简介:此模块有人称为摘要算法,也叫做加密算法,或者是哈希算法,散列算法等等,主要用于密码得加密.文件一致性校验 加密方式有:MD5.sha1.sha25.sha512数字越大,加密的方法越复杂,安全性越高,但是效率就会越慢. 普通加密 import hashlib md5 = hashlib.md5() md5.update('123456'.encode('utf-8')) # 必须是bytes类型才能够进行加密 print(md5.hexdige

Python入门之logging日志模块以及多进程日志

本篇文章主要对 python logging 的介绍加深理解.更主要是 讨论在多进程环境下如何使用logging 来输出日志, 如何安全地切分日志文件. 1. logging日志模块介绍 python的logging模块提供了灵活的标准模块,使得任何Python程序都可以使用这个第三方模块来实现日志记录.python logging 官方文档 logging框架中主要由四个部分组成: Loggers: 可供程序直接调用的接口 Handlers: 决定将日志记录分配至正确的目的地 Filters:

python开发模块基础:collections模块

一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict.namedtuple和OrderedDict等.1.namedtuple: 生成可以使用名字来访问元素内容的tuple2.deque: 双端队列,可以快速的从另外一侧追加和推出对象3.Counter: 计数器,主要用来计数4.OrderedDict: 有序字典5.defaultdict: 带有默