python 常用模块2

hashlib模块

Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。

摘要算法又称哈希算法、散列算法。它通过一个函数,把    任意长度的数据     转换为一个   长度固定的数据串(通常用16进制的字符串表示)。

摘要算法就是通过 摘要函数f()  对  任意长度的数据data  计算出  固定长度的摘要digest,目的是为了发现原始数据是否被人篡改过。

摘要算法之所以能指出数据是否被篡改过,就是因为摘要函数是一个单向函数,计算f(data)很容易,但通过digest反推data却非常困难。而且,对原始数据做一个bit的修改(加盐),都会导致计算出的摘要完全不同。

摘要算法的用处:
1 密码的密文存储(加盐)
2 文件的一致性验证(不需加盐)
在下载的时候 检查我们下载的文件和远程服务器上的文件是否一致
两台机器上的两个文件 你想检查这两个文件是否相等
import hashlib   # 提供摘要算法的模块
md5 = hashlib.md5()
md5.update(b'123456')
print(md5.hexdigest())
#aee949757a2e698417463d47acac93df
sha算法,随着算法复杂程度的增加,摘要的时间成本空间成本都会增加。
import hashlib   # 提供摘要算法的模块
sha = hashlib.sha()
sha.update(b'alex3714')
print(sha.hexdigest())

如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的:

md5 = hashlib.md5()
md5.update('how to use md5 in ')
md5.update('python hashlib?')
print md5.hexdigest()

为了防止撞库,应用加盐算法

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

动态加盐更安全

用户名 密码
使用用户名的一部分或者 直接使用整个用户名作为盐
import hashlib # 提供摘要算法的模块 md5 = hashlib.md5(bytes('',encoding='utf-8')+b'') # md5 = hashlib.md5() md5.update(b'123456') print(md5.hexdigest())

configparser模块

该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

创建文件

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

用configparser创建下面文档(ini)

import configparser
con = configparser.ConfigParser()
con['DEFAULT']={
                    'ServerAliveInterval': '45',
                    'Compression': 'yes',
                    'CompressionLevel': '9',
                    'ForwardX11':'yes'
                }
con['bitbucket.org'] = {'User':'hg'}
con['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini','w') as f:
    con.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模块

有5种级别的日志记录模式 ,两种配置方式:basicconfig 、log对象。
日志 用来记录用户行为 或者 代码的执行过程
函数式简单配置
logging.debug('debug message')          # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('warning message')      # 警告信息(不影响代码逻辑)
logging.error('error message')          # 错误信息(影响逻辑,不能执行)
logging.critical('critical message')    # 高级别的 # 严重错误信息

默认Python的 logging模块 将 日志 打印到 标准输出 中,且只显示了大于等于WARNING级别的日志,默认的级别设置为WARNING,默认的格式为日志级别:Logger名称:用户输出消息。

(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG)

basicConfig配置日志级别,日志格式,输出位置:
import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
  
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'}) #-->value  输出 value

配置参数

logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
View Code

缺点: 简单,能做的事情相对少。

    1 中文的乱码问题
2 不能同时往文件和屏幕上输出

logger对象配置

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')   # 高级别的 # 严重错误信息

logging库提供了多个组件:Logger、Handler、Filter、Formatter

Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可通过:logger.setLevel(logging.Debug)  设置级别,当然,也可以通过   fh.setLevel(logging.Debug)  单对文件流设置某个级别。

原文地址:https://www.cnblogs.com/olivia2018/p/8343556.html