hashlip 摘要算法模块 md5 sha
md5 加密算法 常用算法, 可以满足一般的常用的需求
sha 加密算法 级别高一些, 数字越大级别越高,加密的效率越低,越安全.
#普通的
#加盐的
#动态加盐的
#sha 系列
# 普通的
# 加盐的
# 动态加盐的
# 小文件
# 大文件
import hashlib
#md5
# s1 = '12343254'
# ret = hashlib.md5() # 创建一个md5对象
# ret.update(s1.encode('utf-8')) # 调用此update方法对参数进行加密 bytes类型
# print(ret.hexdigest()) # 得到加密后的结果 定长
s3 = '123456'
# ret = hashlib.md5('@$1*(^&@^2wqe'.encode('utf-8')) # 创建一个md5对象,加盐
# ret.update(s3.encode('utf-8')) # 调用此update方法对参数进行加密 bytes类型
# print(ret.hexdigest()) # 得到加密后的结果 定长 c5f8f2288cec341a64b0236649ea0c37
变成随机的盐:
# username = '爽妹'
# password = '123456'
# ret = hashlib.md5(username[::-1].encode('utf-8'))
# ret.update(password.encode('utf-8'))
# print(ret.hexdigest())
文件的校验
小文件
def func(file_name):
# with open(file_name,mode='rb') as f1:
# ret = hashlib.md5()
# ret.update(f1.read())
# return ret.hexdigest()
#
# print(func('hashlib_file'))
# print(func('hashlib_file1'))
大文件
def func(file_name):
# with open(file_name,mode='rb') as f1:
# ret = hashlib.md5()
# while True:
# content = f1.read(1024)
# if content:
# ret.update(content)
# else:
# break
# return ret.hexdigest()
# print(func('hashlib_file'))
# print(func('hashlib_file1'))
序列化模块 传输和写入文件 还有游戏存档
json pickle shelve
json
两对:
# dumps loads
# dump load
# dic = {"alex": ['women','women','老女人'],'p1':True}
# dic = {"alex": ('women','women','老女人')}
# print(str(dic)) # 基础数据类型str 里面如果有引号就是单引号
# ret = json.dumps(dic,ensure_ascii=False) # 序列化过程:数据类型dic---> 序列化的字符串
# print(ret,type(ret))
# 被json序列化的字符串:
#1,可以直接通过网络互相传输.
#2,可以在各个语言中通用.
# dic1 = json.loads(ret) # 反序列化过程.:将序列化的字符串---> 原有的数据类型.
# print(dic1,type(dic1))
单个文件存储
f = open('json_file',encoding='utf-8',mode='w')
# json.dump(l1,f,ensure_ascii=False) # 将序列化的字符串存储到文件中
# f.close()
# f = open('json_file',encoding='utf-8')
# ret = json.load(f)
# print(ret,type(ret))
# f.close()
多个文件存储
# dic = {"alex": ('women','women','老女人')}
# dic2 = {"alex1": ('women','women','老女人')}
# dic3 = {"alex2": ('women','women','老女人')}
# with open('json_files',encoding='utf-8',mode='a') as f1:
# s1 = json.dumps(dic,ensure_ascii=False)
# f1.write(s1+'\n')
# s2 = json.dumps(dic2,ensure_ascii=False)
# f1.write(s2+'\n')
# s3 = json.dumps(dic3,ensure_ascii=False)
# f1.write(s3+'\n')
#
# with open('json_files',encoding='utf-8') as f2:
# for line in f2:
# dic = json.loads(line)
# print(dic,type(dic))
# dic = {"alex": ('women','women','老女人')}
# ret = "\n"+json.dumps(dic)
# print(ret)
pickle序列化模块,python语言网络交互使用的,他支持所有的python数据类型.
# dumps loads
# dump load
网络传输
dic = {1:True,(2,3):[1,2,3,4],False:{1,2,3}}
# import pickle
# ret = pickle.dumps(dic) # bytes类型无法识别内容
#
# dic1 = pickle.loads(ret)
# print(dic1,type(dic1))
文件存储
with open('pickle_file',mode='wb') as f1:
# pickle.dump(dic,f1)
# with open('pickle_file',mode='rb') as f2:
# print(pickle.load(f2))
多个存储
dic = {"alex": ('women','women','老女人')}
# dic2 = {"alex1": ('women','women','老女人')}
# dic3 = {"alex2": ('women','women','老女人')}
import pickle
# with open('pickle_files',mode='wb') as f1:
# pickle.dump(dic,f1)
# pickle.dump(dic2,f1)
# pickle.dump(dic3,f1)
# pickle.dump(dic3,f1)
# with open('pickle_files',mode='rb') as f1:
# while True:
# try:
# print(pickle.load(f1))
# except EOFError:
# break
time 模块 三种时间的转化
1,时间戳:(测试执行效率 time.time()) *
# 2,格式化时间: strftime() *
# 表示时间.供人类看的.
# print(time.strftime('%Y-%m-%d %H:%M:%S'))
3,结构化时间:time.struct_time(时间戳与字符串时间中间介质.)
# ret = time.localtime() *
格式化时间 ----> 结构化时间
# ft = time.strftime('%Y/%m/%d %H:%M:%S')
# struct_time = time.strptime(ft,'%Y/%m/%d %H:%M:%S')
# print(struct_time)
# 结构化时间 ----> timestamp 时间戳
# timestamp = time.mktime(struct_time)
# print(timestamp)
# timestamp 时间戳 ----> 结构化时间
# timestamp = time.time()
# struct_time = time.localtime(timestamp)
# print(struct_time)
# 结构化时间 ----> 格式化时间
# ft = time.strftime('%Y-%m-%d %H:%M:%S',struct_time)
# print(ft)
# 特殊的转化
# 时间戳 ----> 特殊的格式化时间
# timestamp = time.time()
# ft = time.ctime(timestamp)
# print(ft)
# 结构化时间 ---> 特殊的格式化时间
# struct_time = time.localtime()
# print(struct_time)
# ft = time.asctime(struct_time)
# print(ft)
# struct_time =time.localtime(time.time())
# print(struct_time)
# ft = time.strftime('%Y-%m-%d %H:%M:%S',struct_time)
# print(ft)
# ft1 = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(2900000000))
# print(ft1)
random 模块 随机数
import random
# print(random.random()) # 0~1 之间的小数
# print(random.uniform(1,3)) # 1~3小数
# print(random.randint(1,5)) # 1<=x<=5
# print(random.randrange(1,10,2)) # 1<=x<10 的奇数 顾首不顾尾
# print(random.choice({1,'23',2,3})) # 任选一个 常用
# print(random.choice('fdsjafdsfgdsagfdsa')) # 任选一个 常用
# random.sample([1,1,1,1,1,6,7,8,9,10],2) # #列表元素任意2个组合
# item = [i for i in range(1,14)]
# # random.shuffle(item) # 打乱顺序
# # print(item)
# 1题:4位,全数字的随机验证码
# 2题:4位,数字与字母(不区分)相结合的随机验证码.
logging 日志模式
日志
# import logging
# logging.basicConfig() 基础设置
# logging.getLogger() logger对象设置
1,被动触发: 与异常处理配合.访问记录.
#2, 主动触发:检测运维人员输入的指令,检测服务器的重要信息,访问记录.等等.
低配模式
低配版 low版
# import logging
# logging.basicConfig(level=logging.INFO,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# filename='low版logging.log'
# )
# msg = 'cpu 正常,硬盘参数...,流量的max:..最小值:.....'
# logging.info(msg)
# 日志的信息:不能写入文件与显示 同时进行.
import logging
# logger = logging.getLogger() # 创建logger对象.
# fh = logging.FileHandler('高配版logging.log',encoding='utf-8') # 创建文件句柄
# sh = logging.StreamHandler() #产生了一个屏幕句柄
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# # logger.setLevel(logging.DEBUG)
# #如果你对logger对象设置日志等级.那么文件和屏幕都设置了.
# #总开关 默认从warning开始,如果想设置分开关:必须要从他更高级:(ERROR,critical)从这来个开始.
#
# # 吸星大法
# logger.addHandler(fh) #添加文件句柄
# logger.addHandler(sh) #添加屏幕句柄
# sh.setFormatter(formatter) # 设置屏幕格式
# fh.setFormatter(formatter) # 设置文件的格式 (这两个按照需求可以单独设置)
# fh.setLevel(logging.DEBUG)
collecttions
特殊数据类型
nametuple
deque 可以进行字典的操作 如果是在前添加用他 负责用列表追加
双端队列
# from collections import dequeCOL
# dq = deque()
# dq.append()
# dq.appendleft()
# dq.pop()
# dq.popleft()
# dq.insert()
# dq.index()
默认字典 设置的时候必须是一个callable
#namedtuple
# tu = (1,2)
# print(tu[0],tu[1])
# from collections import namedtuple
# point = namedtuple('Point',['x','y'])
# p = point(10,30) # p = (x=10,y=30)
# print(p.x)
# print(p.y)
# print(p[0])
# print(p[1])
deque 双向队列
# from collections import deque
# q = deque(['a','b','c','d','e'])
# print(q)
# q.append(666) #添加最右边
# q.append(777)
# q.appendleft(111) #从最左边添加
# q.appendleft(222)
# q.pop() # 从右边删除
# q.popleft() # 从左边删除
# q.popleft()
# print(q)
# queue队列 原则:先进先出.fifo
# 栈: 先进后出.
from collections import defaultdict
# l1 = [11, 22, 33,44,55,66,77,88,99,90]
# my_dict = defaultdict(list)
# my_dict['key1']
# my_dict['key2']
# print(my_dict)
# my_dict = defaultdict(list)
# for value in l1:
# if value>66:
# my_dict['k1'].append(value)
# else:
# my_dict['k2'].append(value)
# print(my_dict)
dic1 = {} #---> dic1={1:5,2:5,3:5.....20:5}
# for i in range(1,21):
# dic1[i] = 5
# print(dic1)
# dic1 = {x:5 for x in range(1,21)}
# dic1 = dict.fromkeys(range(1,21),5)
# dic1 = defaultdict(lambda :5)
# for i in range(1,21):
# dic1[i]
# print(dic1)
configgparser 配置文件
# 帮助你操作(创建,增,删,改,查)一个配置文件
# 创建一个文件.
# 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 configfile:
# config.write(configfile)
mport configparser
config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
# print(config.sections()) # []
#
config.read('example.ini')
# 顺序:创建一个对象,然后将文件读到内存中,在进行相应的操作.
#
# print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']
# # #为什么没有 DEFAULT,它是特殊的,可以看做成一个全局的.
# print('111' 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> 可迭代对象
# print(config['bitbucket.org']['forwardx11']) #<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 configparser
#
# config = configparser.ConfigParser()
# # config.read('new2.ini')
# # config.add_section('日天')
# config.remove_section('bitbucket.org')
# config.remove_option('topsecret.server.com',"forwardx11")
#
#
# config.set('topsecret.server.com','k1','11111')
# config.set('yuan','k2','22222')
#
# config.write(open('new2.ini', "w"))
os 模块
print(__file__)本文件夹的绝对路径
print(os.getcwd) 获取执行的文件的的绝对路径
os模块是与操作系统交互的一个接口
os.mkdir("文件夹1") 创建一个文件
os.makedirs("文件夹1\文件夹2")创建多个文件
l1 = os.listdir('E:\sylar\python_workspace\day27')列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()删除一个文件
os.rename()重命名文件
ret = popen("dir").read() print(ret)运行shell命令 获取执行结果
ret = os.path.abspath('04 os 模块.py')获取本文件的绝对路径
print(os.path.split(os.path.abspath('04 os 模块.py')))将path分割成目录和文件名的二元组
print(os.path.join("E:\\sylar\\python_workspace', '\\day28', '\\day29'")) 拼接路径
print(os.path.getsize('E:\\sylar\\python_workspace\\day27\\04 os 模块.py'))
sys模块
# sys.argv
# sys.path
print(sys.argv)
if sys.argv[1] == 'alex' and sys.argv[2] =='alex3714':
print('启动mysql')
# mysql root 123
在终端启动 可以加名字密码 数据库使用较多