博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
常用模块2
阅读量:7045 次
发布时间:2019-06-28

本文共 6381 字,大约阅读时间需要 21 分钟。

一,hashlib模块(摘要算法)

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

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

以MD5为例:

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

注:1,对于相同的字符串使用同一个算法进行摘要,得到的值总是不变的,

    对于不同算法相同字符串进行摘要,得到的值不同。

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

   3,摘要算法,用途:密码的密文存储,文件一致性的验证。

登录验证: # import hashlib# usr=input("username:")# pwd=input("passwodr:")# with open("userinfo") as f:#     for i in f:#         user,passwd=i.split("|")#         md5=hashlib.md5()#         md5.update(bytes(pwd,encoding="utf-8"))#         md5_pwd=md5.hexdigest()#         if usr == user and md5_pwd==passwd:#             print("hi")

1.2加盐与动态加盐

# 加盐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())#import hashilib# 做摘要计算的 把字节类型的内容进行摘要处理# md5 sha# md5  正常的md5算法 加盐的 动态加盐
View Code

1.3

可多次更新(一次更新一部分)最后结果和一次性更新是一样的import hashlib sha1 = hashlib.sha1()sha1.update('how to use sha1 in ')sha1.update('python hashlib?')print sha1.hexdigest()
多次更新

2,logging模块

函数式简单配置

# import logging# logging.debug("debug message")       #排错信息# logging.info("info message")         #正常信息# logging.warning("warning message")    #警告信息# logging.error("error message")        #错误信息# logging.critical("critical message")  #严重错误

注:默认情况下只显示大于warning级别的日志包括(warning)。

2.1 basicConfig(简单,功能相对少)

 注:1,写入文件时:如果是中文会产生乱码

   2,不能同时写入文件和在屏幕上输出

写入日志文件#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',#                     filename="test.log",#                     filemode="a")#  logging.debug("debug message")       # logging.info("info message")         # logging.warning("warning message")    # logging.error("error message")        # logging.critical("critical message") #在屏幕输出# 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')#  logging.debug("debug message")       # logging.info("info message")         # logging.warning("warning message")    # logging.error("error message")        # logging.critical("critical message")
View Code

配置参数:

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用户输出的消息
配置参数

2.2 logger (稍微复杂,功能相对多)

import logginglogger = logging.getLogger()# 创建一个handler,用于写入日志文件fh = logging.FileHandler('test.log',encoding='utf-8') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setLevel(logging.DEBUG)fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 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')
logger对象配置
logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别,当然,也可以通过fh.setLevel(logging.Debug)单对文件流设置某个级别

注:logging,有两种配置方式(basicConfig,log对象),有五种级别的日志记录模式。

3,configparser模块

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

3.1 创建文件

 

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes  [bitbucket.org]User = hg  [topsecret.server.com]Port = 50022ForwardX11 = no
常见文档格式

3.11 python生成常见文档

import configparserconfig = 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)
View Code

3.2 查找文件

import configparserconfig = configparser.ConfigParser()#---------------------------查找文件内容,基于字典的形式print(config.sections())        #  []config.read('example.ini')print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']print('bytebong.com' in config) # Falseprint('bitbucket.org' in config) # Trueprint(config['bitbucket.org']["user"])  # hgprint(config['DEFAULT']['Compression']) #yesprint(config['topsecret.server.com']['ForwardX11'])  #noprint(config['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
View Code

3.3 增删改操作

# 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()
View Code

 

转载于:https://www.cnblogs.com/glf1160/p/8342552.html

你可能感兴趣的文章
我的友情链接
查看>>
表示数值的字符串
查看>>
高级运维工程师的打怪升级之路
查看>>
Mysql的一些优化(my.cnf)
查看>>
PowerShell检测并添加用户权限
查看>>
CCNP笔记——MST上
查看>>
php5中const、define和static
查看>>
HNUSTOJ-1695 跳格子(略感头疼)
查看>>
Python 代码规范
查看>>
DNS服务的配置与管理(2) DNS的理论知识
查看>>
2.Apache + Tomcat + mod_jk实现集群服务
查看>>
1.jeesite环境搭建
查看>>
Android实践项目汇报(四)
查看>>
destoon去掉会员注册email验证
查看>>
Python单元测试
查看>>
MySQL数据库的创建&删除&选择
查看>>
CSS 实践:实现下拉菜单的方法
查看>>
手机扫一扫车牌即可识别出结果的sdk
查看>>
初级程序员面试不靠谱指南(五)
查看>>
CF1109F Sasha and Algorithm of Silence's Sounds
查看>>