常用模块(hashlib,configparser,logging)

hashlib

hashlib 摘要算法的模块
md5 sha1 sha256 sha512
摘要的过程 不可逆
能做的事:
文件的一致性检测
用户的加密认证 单纯的md5不够安全 加盐处理 简单的盐可能被破解 且破解之后所有的盐都失效 动态加盐

md5 = hashlib.md5()  # 选择摘要算法中的md5类进行实例化,得到md5_obj
md5.update(b'how to use md5 in python hashlib?') # 对一个字符串进行摘要
print(md5.hexdigest()) # 找摘要算法要结果

一篇文章的校验
读文件:一行一行拿
转换成bytes

文件1
文件2
分别打开两个文件,一行一行读,每一行update一下,对比最终的hexdigest

查看某两个文件是否完全一致 —— 文件的一致性校验

加密认证 —— 在存储密码的时候使用密文存储,校验密码的时候对用户的输入再做一次校验

import hashlib
md5 = hashlib.md5()
md5.update(b'alex3714') pwd = input('')
md5 = hashlib.md5()
md5.update(b'alex3714')

加盐
动态加盐
用户名 + 一个复杂的字符串 + 密码

import hashlib
md5 = hashlib.md5(b'suger')
md5.update(b'alex3714')

configparser

文件格式如下

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

想用python生成一个这样的文档怎么做

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)

相关操作

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') # 添加一个组
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")) # write的时候才生效

为什么要有配置文件:在程序外修改一些配置
配置文件其实是多种多样的
configparser是专门解决一种样式的配置文件而生的
yaml 是另一种配置规则 python也提供了扩展模块

logging

日志 在程序的运行过程中,人为的添加一些要打印的中间信息
在程序的排错、在一些行为、结果的记录

import logging
logging.debug('debug message') # 调试模式:不是必须出现,但是如果有问题需要借助它的信息调试
logging.info('info message') # 信息模式:必须出现但是对程序正常运行没有影响
logging.warning('warning message') # 警告模式:不会直接引发程序的崩溃,但是可能会出问题
logging.error('error message') # 错误模式:出错了
logging.critical('critical message') # 批判模式:程序崩溃了的时候

logging 简单的配置模式

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')

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

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”
format:指定handler使用的日志显示格式
datefmt:指定日期时间格式
level:设置rootlogger(后边会讲解具体概念)的日志级别

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用户输出的消息

logging 高级的使用对象配置的模式

logger = logging.getLogger()  # 实例化一个logger对象
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding='utf-8') # 文件句柄-日志文件操作符
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler() # 屏幕流对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 日志输出格式
logger.setLevel(logging.DEBUG) # 设置日志等级,默认是Warning
fh.setFormatter(formatter) # 文件句柄绑格式
ch.setFormatter(formatter)
logger.addHandler(fh) # logger绑文件句柄
logger.addHandler(ch)
logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

logging
basicConfig:
配置简单,配了就能直接用
对象模式:
可以随意的控制往哪些地方输出日志
且可以分别控制输出到不同位置的格式

最新文章

  1. 二分K-means算法
  2. JAVA String,StringBuffer与StringBuilder的区别??
  3. js跳转传递参数
  4. 13款经典BI项目报表&amp;界面风格设计方案
  5. Saltstack grains组件
  6. 二、JavaScript语言--JS实践--商城分类导航效果
  7. Data conversion error converting
  8. c point ccccc
  9. struts2中form提交到action中的中文参数乱码问题解决办法(包括取中文路径)
  10. EF架构~过滤导航属性等,拼接SQL字符串
  11. Linux nohup命令详解
  12. appcan里面模板的使用
  13. IIC 概述之3
  14. arcgis api for silverlight
  15. 最新 Cocos2d-x 3.2 开发环境搭建(windows环境下)
  16. 【Ubuntu Desktop】VMware 中 Unknown Display
  17. springboot注解使用说明
  18. ArrayDataProvider数据分页
  19. BUG关闭原因
  20. 魔术方法__get()、__set()和__call()的用法

热门文章

  1. C扩展php的方法(制作php扩展库)
  2. hdu5745 La Vie en rose 巧妙地dp+bitset优化+滚动数组减少内存
  3. 【JMeter4.0】之遇到的问题总结(持续更新)
  4. node.js和前端js有什么区别
  5. cocos2dx-是男人就坚持20s 练手项目
  6. 维纳滤波和编码曝光PSF去除运动模糊【matlab】
  7. OSX终端 命令行的一些基本操作
  8. AtCoder Tak and Hotels
  9. 智力大冲浪(洛谷P1230)
  10. 170306、wamp中的Apache开启gzip压缩提高网站的响应速度