欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

day19(random,json,pickle,hashlib,shutil,hmac,shelve 模块)

程序员文章站 2022-04-14 18:33:08
一,复习 二,random模块: 三,json模块: 四,pickle模块: 五,shelve 模块: 六,hashlib加密模块: 七,hmac 加密模块: 八,shutil 模块: ......

一,复习

'''
项目开发规范
atm
    -- bin: 可执行文件
        # run.py
        import os
        import sys
        base_dir = os.path.dirname(os.path.dirname(__file__))  # atm文件夹
        sys.path.append(base_dir)
        
        from core import main
        
    -- core:核心代码
        # main.py
        from setting import settings
        from lib import mp
        
        # login.py
        # from bin.run import base_dir
        # u_info = os.path.join(base_dir, 'db', 'user.info')
        from setting.settings import user_info
        
        # register.py
        # from bin.run import base_dir
        # u_info = os.path.join(base_dir, 'db', 'user.info')
        from setting.settings import user_info

    -- db:数据库
        # user.info
        
    -- setting:配置
        # settings.py
        from bin.run import base_dir
        user_info = os.path.join(base_dir, 'db', 'user.info')
        
        
    -- lib:公用模块
        # mp文件夹
            __init__.py
            m1.py
            m2.py
        
    
    -- log:日志
    -- static:静态资源
    -- interface:接口


2.时间: time calendar datetime

3.系统 sys, os, os.path

4.sys.argv:结束文件作为脚本执行传入的参数
cmd:python3 py脚本 参数们
'''

 

二,random模块:

'''
(0,1):random.random()
[1,10]:random.randint(1,10)
[1,10):random.randrange(1,10)
(1,10):random.uniform(1,10)
单例集合随机选择1个:random.choice(item)
单例集合随机选择n个:random.sample(item,n)
洗牌单例集合:random.shuffle(item)
'''''

import random

for i in range(10):
    print(random.random())      #0.7752135892961534  ... 0.4973644933984488

for i in range(10):
    print(random.randint(1,10)) #[1,10]整数

for i in range(10):
    print(random.randrange(1,10)) #[1,9]整数

for i in range(10):
    print(random.uniform(1,10))     #(1,10)小数

item = [1, 2, 3, 4, 5]
for i in range(10):
    print(random.choice(item))  #随机选择一个,选择10次

for i in range(10):
    print(random.sample(item,3))    #[5, 2, 1] ....[2, 4, 3]

# 打乱
random.shuffle(item)    #[4, 3, 1, 5, 2]
# print(item)


'''#验证码案例:'''
#part1
def random_code0(num):
    code = ''
    for i in range(num):
        d = random.randint(65, 90)   # 小写字母
        x = random.randint(97, 122)  # 大写字母
        n = random.randint(0, 9)
        code += random.choice([chr(d),chr(x),str(n)])
    return code
res = random_code0(10)
print(res)

#part2 def random_code1(num): code = '' for i in range(num): choose = random.randint(1,3) if choose == 1: c = chr(random.randint(65,90)) elif choose == 2: c = chr(random.randint(90,122)) else: c = str(random.randint(0,9)) code += c return code res1 = random_code1(10) print(res1) #print(ord(']')) #93 #part3 def random_code2(num): #每个字母只会出现一次 target = '1234567890qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm~!@#$%^&*()_+' code_list = random.sample(target,num) return ''.join(code_list) res2 = random_code2(10) print(res2)

 

三,json模块:

'''
json语言,就是一种语法规范的字符串,用来存在数据的,完成各种语言之间的数据交互
1,就是{} 与 []的组合,{}存放双列信息(类比字典),[]存放单列信息(类比列表)
2,{}的key必须是字符串,且必须用 "" 包裹
3,{}与[]中支持的值得类型有:dict| list | int | float | bool | null | str 
'''
json_str = '{"info" : 1,"msg": [1 ,"a" , true , false , null , 3,14]}' obj = json.loads(json_str)
#在python环境下会转换为python下的格式 print(obj, type(obj)) #{'info': 1, 'msg': [1, 'a', true, false, none, 3, 14]} <class 'dict'> ''' 序列化:将对象转换为字符串 dumps:将对象直接序列化成字符串 ''' obj = {'name':'owen',"age":18,'height':180,"gender":"男"} r1 = json.dumps(obj,ensure_ascii=false) #取消默认ascii编码,,同该文件的编码utf-8,py3默认utf-8,py2规定文件头 print(r1) #{"name": "owen", "age": 18, "height": 180, "gender": "男"} ''' dump:将对象序列化成字符串存储到文件中 ''' with open('1.txt','w',encoding='utf-8')as w: json.dump(obj,w,ensure_ascii=false) ''' 反序列化:将字符串转换为对象 ''' json_str ='{"name":"owen","age":18,"height":180,"gender":"男"}' r2 = json.loads(json_str,encoding='utf-8') #默认跟当前文件解释器执行编码走 print(r2,type(r2)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'dict'> with open('1.txt','r',encoding='utf-8')as r: data = json.load(r) print(data,type(data)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'dict'>

 

四,pickle模块:

obj = {"name":'owen',"age":18,"height":180,"gender":"男"}
'''eval''' s = str(obj) print(s,type(s)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'str'> o = eval(s) print(o,type(o)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'dict'> ''' 为什么有很多序列化和反序列化模块 因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化 只有序列化存储后,必须有对应的反序列化,才能保证存储的数据被重新读取使用 什么是序列化: 对象=》字符串 为什么序列化:存(pickle) 和 传(json) 为什么要反序列:再次使用 为什么有很多序列化模块:存与取的算法可以多种多样,且要配套 ''' import pickle obj = {"name":'owen',"age":18,"height":180,"gender":"男"} #序列化 r1 = pickle.dumps(obj) print(r1) #b'\x80\x03}q\x00(x\x04\x00\x00\x00nameq\x01x\x04\x00\x00\x00owenq\x02x\x03\x00\.......94\xb7q\x06u.' with open('2.txt','wb')as w: pickle.dump(obj,w) #反序列化 with open('2.txt','rb')as r: data = r.read() o1 = pickle.loads(data) print(o1,type(o1)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'dict'> r.seek(0,0) #游标移到开头在读 o2 = pickle.load(r) print(o2,type(o2)) #{'name': 'owen', 'age': 18, 'height': 180, 'gender': '男'} <class 'dict'>

 

五,shelve 模块:

'''
即时存取的序列化模块
'''''
import shelve

shv_dic = shelve.open('my.shv')
shv_dic['name'] = 'owen'
shv_dic['nmae'] = 'zero'
shv_dic.close()

#关闭后需要重新open才能读
# print(shv_dic['name'])

shv_dic = shelve.open('my.shv')
print(shv_dic['name'])      #owen

stus = ['张三','李四']
shv_dic['stus'] = stus
print(shv_dic['stus'])
shv_dic.close()             #['张三', '李四']


shv_dic = shelve.open('my.shv',writeback=true)
#将内容从文件中取出,在内存中添加,如果操作文件有writeback=true,会将内存操作记录实时同步到文件
shv_dic['stus'].append('王五')
print(shv_dic['stus'])    #['张三','李四','王五']
shv_dic.close()    


#方式二:利用一个缓存的变量
# ls = []
# she = shelve.open('my.shv')
# stus = ['张三','李四']
# ls = stus
# temp = ls
# temp.append('王五')
# ls = temp
# print(ls)

import shelve
list = [1, 2, 3]
she = shelve.open('test')
she['d'] = list
print(she['d'])
temp = she['d']
temp.append('f')
she['d'] = temp
print(she['d'])

 

六,hashlib加密模块:

''''
不可逆加密:没有解密的加密方式 md5
解密方式:碰撞解密
加密的对象:用于传输的数据(字符串类型数据)
'''''

import hashlib
lock = hashlib.md5()

# 195eaff9c88bceae9f094f5ef322e5da
data = '你好帅'
lock.update(data.encode('utf-8'))

#195eaff9c88bceae9f094f5ef322e5da
lock.update('你'.encode('utf-8'))
lock.update('好'.encode('utf-8'))
lock.update('帅'.encode('utf-8'))

res = lock.hexdigest()
print(res)

'''
特点:加密的总数据一样,加密结果一定一样,且算法不变,加密结果的长度不变
'''


'''
一次加密:
1,获取加密对象  hashlib.md5() => lock_obj
2,添加加密数据 lock_obj.update(b'...')  ... lock_obj.update(b'...')
3,获取加密结果 lock.hexdigest() => result 
'''
lock = hashlib.md5()
lock.update(b'')    #d41d8cd98f00b204e9800998ecf8427e
res = lock.hexdigest()
print(res)


'''
加盐加密:
1,保证原数据过于简单,通过复杂的盐也可以提高解密难度
2,即使被碰撞解密成功,也不能直接识别盐与有效数据
'''
lock_obj = hashlib.md5()
lock.update(b'goodgoods')
lock_obj.update(b'123')
lock_obj.update(b'upup')
res = lock_obj.hexdigest()
print(res)      #4e8beac37b1af87849fcbacbb534cbd3


#67b176705b46206614219f47a05aee7ae6a3edbe850bbbe214c536b989aea4d2
lock_obj = hashlib.sha3_256(b'1')
print(lock_obj.hexdigest())

#ca2c70bc13298c5109ee0cb342d014906e63652......
lock_obj = hashlib.sha3_512(b'1')
print(lock_obj.hexdigest())

 

 

七,hmac 加密模块:

'''
hmac加密:
'''''
import hmac
#hmac.new(arg)      #区别:必须提供一个参数

cipher = hmac.new('加密的数据'.encode('utf-8')) print(cipher.hexdigest()) #786d0bc4850b2f4daf6b293a3df23653 cipher = hmac.new('前盐'.encode('utf-8')) cipher.update('加密的数据'.encode('utf-8')) print(cipher.hexdigest()) #786d0bc4850b2f4daf6b293a3df23653 cipher = hmac.new('加密的数据'.encode('utf-8')) cipher.update('后盐'.encode('utf-8')) print(cipher.hexdigest()) #e785c73fd63568fabf047ed5ec280a15 cipher = hmac.new('前盐'.encode('utf-8')) cipher.update('加密的数据'.encode('utf-8')) cipher.update('后盐'.encode('utf-8')) print(cipher.hexdigest()) #fdf226ffcf70e1ab56100bc88fa594a0

 

八,shutil 模块:

'''
shutil : 可以操作权限的处理文件模块
'''''
import shutil

'''
1,基于路劲的文件复制:
shutil.copyfile(文件1,文件2):文件1直接覆盖copy给文件2
'''
shutil.copyfile(r'd:\python_project\classroom\day19\1,random模块.py',r'd:\python_project\classroom\day19\part1\m1.py')
''' 2,基于流的文件复制: shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2 '''
with open('d:\python_project\classroom\day18\\time模块.py','rb')as r,open('d:\python_project\classroom\day19\part1\m1.py','wb')as w: shutil.copyfileobj(r,w)
''' 3,递归删除目标目录 shutil.rmtree(目标目录):可以递归删除目录下的目录及文件。 '''
shutil.rmtree(r'd:\python_project\classroom\part7')
''' 4,文件移动 shutil.move(源文件,指定路径):递归移动一个文件。 '''
shutil.move(r'd:\python_project\classroom\day19\1.txt',r'd:\python_project\classroom\day19\part1') ''' 5,文件夹压缩 file_name:被压缩后形成的文件名 format:压缩的格式,压缩包种类,“zip”, “tar”, “bztar”,“gztar” archice_path:要被压缩的文件夹路径 shutil.make_archive('file_name','format','archice_path') ''' shutil.make_archive('d:\python_project\classroom\day19\\1,random模块.py','zip','d:\python_project\classroom\day19\part1')
''' 6,文件夹解压 unpack_file :被解压文件 unpack_name :解压后的名字 format :解压格式 shutil.unpack_archive('unpack_file','unpack_name','format') '''

shutil.unpack_archive('d:\python_project\classroom\day19\\1,random模块.py.zip','d:\python_project\classroom\day19\part1','zip')