笔记:python基础之模块——hashlib、configparse&logging

一、摘要算法 hashlib
常用算法:md5,SHA1,sha3_5244,md5为常用算法
两个字符串 :

import hashlib   # 提供摘要算法的模块
md5 = hashlib.md5()
md5.update(b'123456')#转为密文
print(md5.hexdigest())#查看密文
#输出:
e10adc3949ba59abbe56e057f20f883e

hashlib:

  • 不管算法多么不同,摘要的功能始终不变
  • 对于相同的字符串使用同一个算法进行摘要,得到的值总是不变的
  • 使用不同算法对相同的字符串进行摘要,得到的值应该不同
  • 不管使用什么算法,hashlib的方式永远不变

sha 算法: 随着 算法复杂程度的增加,摘要的时间成本、空间成本都会增加

import hashlib   # 提供摘要算法的模块
sha = hashlib.md5()
sha.update(b'alex3714')
print(sha.hexdigest())
#输出:
aee949757a2e698417463d47acac93df

摘要算法应用
1.密码的密文存储
2.文件的一致性验证

  • 在下载的时候 检查我们下载的文件和远程服务器上的文件是否一致
  • 两台机器上的两个文件 你想检查这两个文件是否相等

应用举例:
应用于用户信息的存储。

# 用户的登录
import hashlib
usr = input('username :')
pwd = input('password : ')
with open('userinfo') as f:
    for line in f:
        user,passwd,role = line.split('|')
        md5 = hashlib.md5()
        md5.update(bytes(pwd,encoding='utf-8'))#update(b'')→可多次计算,用于文件一致性校验
        md5_pwd = md5.hexdigest()#明文的密码进行摘要 拿到一个密文的密码
        if usr == user and md5_pwd == passwd:
            print('登录成功')

为避免撞库(密码被破解),对密文进行加盐

import hashlib   # 提供摘要算法的模块
md5 = hashlib.md5(bytes('盐',encoding='utf-8'))#盐可为任意的
#md5 = hashlib.md5()
md5.update(b'123456')
print(md5.hexdigest())
#输出:
970d52d48082f3fb0c59d5611d25ec1e

更复杂安全的方式——动态加盐:使用用户名的一部分或者直接使用整个用户名作为盐。

import hashlib   # 提供摘要算法的模块
md5 = hashlib.md5(bytes('盐',encoding='utf-8')+b'')
# md5 = hashlib.md5()
md5.update(b'123456')
print(md5.hexdigest())

二、背景颜色和字体颜色的设置

print('\033[1;33;44m')#设置背景颜色和字体颜色
print('夜半钟声到客船')
print('商女不知亡国恨')
print('隔江犹唱后庭花')
print('\033[0m')#为字体设置的终端,
print('夜泊秦淮')

三、configparse模块
处理配置文件的模块

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 configparser
config = configparser.ConfigParser()
config.read('example.ini')   # 读文件
config.add_section('yuan')   # 增加section
config.remove_section('bitbucket.org')   # 删除一个section
config.remove_option('topsecret.server.com',"forwardx11")  # 删除一个配置项
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
f = open('new2.ini', "w")
config.write(f) # 写进文件
f.close()

四、logging日志模块
日志:用来记录用户行为 或者 代码的执行过程
logging日志的作用:

  • 我能够“一键”控制
  • 排错的时候需要打印很多细节来帮助我排错
  • 严重的错误记录下来
  • 有一些用户行为 有没有错都要记录下来

5种级别的日志记录模式 :
两种配置方式:basicconfig 、log对象

basicconfig 简单 但能做的事情相对少,存在中文的乱码问题,不能同时往文件和屏幕上输出。

import logging
logging.basicConfig(level=logging.WARNING,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')
try:
    int(input('num >>'))
except ValueError:
    logging.error('输入的值不是一个数字')
logging.debug('debug message')       # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('warning message')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message') # 高级别的 # 严重错误信息

print('%(key)s'%{'key':'value'})
print('%s'%('key','value'))

配置log对象 稍微有点复杂 能做的事情相对多

import logging
logger = logging.getLogger()
fh = logging.FileHandler('log.log',encoding='utf-8')
sh = logging.StreamHandler()    # 创建一个屏幕控制对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] : %(message)s')
# 文件操作符 和 格式关联
fh.setFormatter(formatter)
sh.setFormatter(formatter2)
# logger 对象 和 文件操作符 关联
logger.addHandler(fh)
logger.addHandler(sh)
logging.debug('debug message')       # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('警告错误')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message') # 高级别的 # 严重错误信息

日志的作用:

  • 程序的充分解耦
  • 让程序变得高可定制
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值