zoukankan      html  css  js  c++  java
  • python笔记(22)--hashlib和logging模块详解

    DAY24

    今日内容

    • hashlib
    • logging

    内容详细

    1.hashlib模块:摘要算法的模块

    • sha加密:算法加密

      import hashlib
      sha  = hashlib.sha1()
      sha.update(b'alec8868')     #必须转换成bytes类型
      print(sha.hexdigest())		
      #sha 算法随着算法复杂程度的增加,对比的时间增加和占用内存
      
    • MD5加密:非常普遍的算法

      #例子:用户登录:用文件中的md5加密和用户输入的密码比对
      import hashlib
      user = input('username:')
      pwd = input('password:')
      with open('db.txt','r',encoding='utf-8')as f:
          for line in f:
              usr,password,role = line.split('|')
              md5 = hashlib.md5()
              md5.update(bytes(pwd,encoding='utf-8'))		#必须用bytes类型
              md5_pwd = md5.hexdigest()
              if usr == user  and md5_pwd == password:
                  print('登录成功')
              else:
                  print('登录失败!')
      
    • 加严MD5加密:静态方式

      import hashlib
      md5 = hashlib.md5(bytes('aeiou',encoding='utf-8'))  #加严
      md5.update(b'li456')
      print(md5.hexdigest())
      
    • 加严MD5加密:动态方式(目前最严格的加严方式)

      import hashlib
      user = input('username:')
      pwd = input('password:')
      md5 = hashlib.md5(bytes('aeiou',encoding='utf-8') + bytes(user[2:],encoding='utf-8'))  #可以用用户名的某一个字段来加严
      md5.update(b'li456')
      print(md5.hexdigest())
      
      #注册+登录
      import hashlib
      
      def pwd_md5(user,pwd):
          md5 = hashlib.md5(bytes('aeiou',encoding='utf-8') + bytes(user[2:],encoding='utf-8'))
          md5.update(bytes(pwd,encoding='utf-8'))
          return md5.hexdigest()
      
      user_in = input('username:')
      pwd_in = input('password')
      
      md5_pwd = pwd_md5(user_in,pwd_in)
      with open('db.txt','a+',encoding='utf-8')as f1:
          f1.write('%s|%s|%s
      '%(user_in,md5_pwd,'Teacher'))
          print('注册成功')
      
      print('------------登录-------------')
      user = input('username:')
      pwd = input('pwd:')
      result = pwd_md5(user,pwd)
      flag = False
      with open('db.txt','r',encoding='utf-8')as f2:
          for line in f2:
              use,pawd,roid = line.split('|')
              if user == use and result == pawd:
                  flag = True
      if flag:
          print('登录成功')
      else:
          print('登录失败')
      
    • md5分次加密,一般用在大文件校验上,多次读取

      import hashlib
      md5 = hashlib.md5
      md5.update(b'liya')
      md5.update(b'nan')      #可以分次加密
      print(md5.hexdigest())  #结果和liyanan加密结果一致
      
    • 应用场景:

      • 密码的密文存储
      • 文件的一致性验证
        • 在下载的时候,检查我们下载的文件和远程服务器上的文件是否一致(无需加严)
        • 两台机器上的两个文件,你想检查这两个文件是否相等

    2.logging模块:操作日志记录(非常重要)

    • 警告级别:

      import logging
      
      logging.debug('debug message')      #低级别:排错信息,默认不显示
      logging.info('info message')        #正常信息,默认不显示
      logging.warning('warning message')  #警告信息,默认显示
      logging.error('error message')      #错误信息,默认显示
      logging.critical('critical message')#最高级别:严重错误信息,默认显示
      

    2.1 basicconfig

    • 简单,但能做的事情相对少
    • 问题1:中文乱码问题,因为不能定制编码
    • 问题2:不能同时在文件和控制台上输出
    import logging
    logging.basicConfig(level = logging.DEBUG,  #定制显示debug级别以上的所有告警
                        format='%(asctime)s %(filename)s[line:%(lineno)d]s %(levelname)s %(message)s',
                        datefmt='%a,%d %b %Y %H:%M:%S',
                        filename='test.log',	#输出到文件中
                        filemode='a'			#默认为a或w形式写入文件
    )
    

    2.2 配置logger对象方式(推荐使用)

    • 选择日志输出到log文件上

      import logging
      
      logger = logging.getLogger()        #选择日志输出
      fh = logging.FileHandler('log.log',encoding='utf-8')    #打开日志文件
      formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#定制输出格式
      
      # 设置告警级别:默认为warning
      # sh.setLevel(logging.ERROR)        #只能设置warning以上的告警级别
      # logging.root.setLevel(logging.INFO)   #使用root设置告警级别,5级全部可设置
      
      #把以上三个句柄绑定串联在一起
      #第一步:先将文件操作符 和 格式 关联
      fh.setFormatter(formatter)
      #第二步:再将logger对象 和 文件操作符 关联
      logger.addHandler(fh)
      
      logging.debug('debug message')
      logging.info('info message')
      logging.warning('警告信息')
      logging.error('error message')
      logging.critical('critical message')
      
    • 选择日志输出到屏幕上(可与输出到文件上同时使用,注意变量名对应关系)

      import logging
      
      logger = logging.getLogger()        #选择日志输出
      sh = logging.StreamHandler()       #创建一个屏幕控制对象
      formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] - %(message)s')#定制输出格式
      
      # 设置告警级别:默认为warning
      # sh.setLevel(logging.ERROR)        #只能设置warning以上的告警级别
      # logging.root.setLevel(logging.INFO)   #使用root设置告警级别,5级全部可设置
      
      sh.setFormatter(formatter2)        #将文件操作符 和 格式关联
      logger.addHandler(sh)              #再将logger对象与文件操作符关联
      
      logging.debug('debug message')
      logging.info('info message')
      logging.warning('警告信息')
      logging.error('error message')
      logging.critical('critical message')
      

    2.3 log总结

    • 5种告警级别: CRITICAL > ERROR > WARNING > INFO > DEBUG
    • 两种配置方式:
      • basicconfig:只能完成一些简单的日志记录
      • logger对象方式:高定制化,推荐使用
  • 相关阅读:
    butterknife异常提示:attribute value must be constant
    SharedPreferences第一次使用后HashMap将常驻内存
    js获取元素的innerText属性为什么为空
    针对focus和blur的Dom事件触发顺序
    android中View的GONE和INVISIBLE的原理
    HTML中div以及span等元素获取焦点
    android MotionEvent获得当前位置
    IE10 透明背景的div无法遮罩
    jquery中.attr('value')和.val()的区别
    __proto__和protaotype的区分
  • 原文地址:https://www.cnblogs.com/lynlearnde/p/12938813.html
Copyright © 2011-2022 走看看