hashlib、pickle、hmac、logging模块使用

模块

一、hashlib

1)概念:对字符进行加密(将字符转化成另一种字符)

2)作用:

1、对字符进行加密
2、校验传输的文件是否完整
import md5
m=hashlib.md5()#相对于其他的难以破解
pwd="helloword".encode("utf-8")#pwd=b"helloword"
m.update(pwd)  #进行hash
print(m.hexdigest())

3)特点:

1、hashlib的字符的长度是一样的

2、只要hashlib加密的内容一样,hashlib的结果就是一样的

3、入股使用用一个哈希编码表,他的结果会累加

import hashlib
m=hashlib.md5()
a="123".encode("utf-8")
b="234".encode("utf-8")
m.update(a)
m.update(b)#哈希的内容会叠加
print(m.hexdigest())

4)应用:

#通过hashlib撞库进行破解密码
pwd_list={
  "1234","1234"
}
def break_pwd(true_pwd):
for pwd in pwd_list:
  m.hashlib()
  m.update(pwd.encode("utf8"))
  if m.hexdigest()==true_pwd:
    return pwd
if __name__="__main__":
  true_pwd="123"
  res=break_pwd(true_pwd)
  print("这是正确的密码:",res)

二、hmac

1)用法

import hmac
m=hmac.new(b"1234")#只要new的值不同hmac的值也就不同
m.update(b"pwd")
print(m.hexdigest())
#还可以继续叠加
m.update(b"pwd1")
print(m.hexdigest())

三、uuid

1)概念:利用时间的进行输出,永不重复

for i in range(10):
  print(uuid.uuid4())

四、logging

1)作用:记录日志,对程序重要的过程进行信息保存

2)使用

v1版本
import logging
#info(没有任何问题)  |  debug(没有任何问题)  |  warning(可以去做也可以不去做)  |  error   critical(程序崩溃)
logging.info()
logging.debug()
logging.warning()
logging.error()
logging.critical()
v2版本
import logging
#info(没有任何问题)  |  debug(没有任何问题)  |  warning(可以去做也可以不去做)  |  error   critical(程序崩溃)
#设置日志的版本
logging.basicConfig(filename='info_log.log',#日志存储文件名
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',#设置日志的格式
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)#日志的显示登记
logging.info("123")  #10
logging.debug("123")  #20
logging.warning("123") #30
logging.error("123") #40
logging.critical("123") #50
#输入结果:只能打印warning以上的日志
v3版本(自定义版本)
import logging
#设置logging的类型
logger=logging.getLogger("bank")
#设置日志存储的位置
t1=logging.FileHandler("t1.txt")
t2=logging.FileHandler("t2.txt")
t3=logging.StreamHandler()#打印到屏幕
#定义日志的格式
#第一种格式
formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)
#第二种格式
formmater2=logging.Formatter('%(asctime)s :  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',)
#第三种格式
formmater3=logging.Formatter('%(name)s %(message)s',)
#对Handler对象绑定日志格式
t1.setFormatter(formatter1)
t2.setFormatter(formatter2)
t3.setFormatter(formatter3)
#将Hanler对象添加给logger,并设置日志登记
logger.addHandler(t1)
logger.addHandler(t2)
logger.addHandler(t3)
logger.setLevel(10)
#测试
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
v4终极版本及修改
"""
logging配置
"""

import os
import logging.config

# 定义三种日志输出格式 开始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 
                  '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定义日志输出格式 结束

logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录

logfile_name = 'all2.log'  # log文件名

# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        #logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例
    logger.info('It works!')  # 记录该文件的运行状态
原文地址:https://www.cnblogs.com/chuwanliu/p/11005695.html