python基础知识(七)常用模块----(七)

(七)常用模块----(七)

目录

(七)常用模块----(七)

7.1hashlib

7.2configparser

7.3logging


 

7.1hashlib

hashlib模块:摘要算法,是一个提供把字符串转化为一个十六进制固定长度的数

                       对一个相同的字符串,使用同一个算法得到的值始终是相同的

import hashlib
md5 = hashlib.md5()
md5.update(b'123')
print(md5.hexdigest())

#202cb962ac59075b964b07152d234b70

摘要算法:a.密码的密文存储

                  b.文件的一致性验证

                         1.在下载的时候 检查我们下载的文件和远程服务器上的文件是否一致

                          2.两台机器上的两个文件 你想检查这两个文件是否相等

模仿用户注册,用户登录

#用户注册
import hashlib
username = input('请输入您的用户名:')
password = input('请输入您的密码:')
md5 = hashlib.md5()
md5.update(bytes(password,encoding='utf-8'))

with open('userinfo.py',mode='a',encoding='utf-8') as f:
    f.write(username)
    f.write('|')
    f.write(md5.hexdigest())
#用户的登录
usr = input('username :')
pwd = input('password : ')
with open('userinfo.py') as f:
    for line in f:
        user,passwd = line.split('|')
        md5 = hashlib.md5()
        md5.update(bytes(pwd,encoding='utf-8'))
        md5_pwd = md5.hexdigest()
        if usr == user and md5_pwd == passwd:
            print('登录成功')
        else:
            print('登录失败')

加盐

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

动态加盐

#动态加盐
import hashlib 
md5 = hashlib.md5(bytes('salt',encoding='utf-8')+b'')
# md5 = hashlib.md5()
md5.update(b'123456')
print(md5.hexdigest())

7.2configparser

configparser模块:读取ini类型的配置文件

#创建
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)
'''
user
serveraliveinterval
compression
compressionlevel
forwardx11
'''

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

7.3logging

logging模块:日志模块

import logging
logging.debug('debug message')       # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('warning message')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message') # 高级别的 # 严重错误信息
'''
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
'''

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

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

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')
'''
Wed, 08 May 2019 14:18:38 02 logging.py[line:29] WARNING warning message
Wed, 08 May 2019 14:18:38 02 logging.py[line:30] ERROR error message
Wed, 08 May 2019 14:18:38 02 logging.py[line:31] CRITICAL critical message
'''
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用户输出的消息
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') # 高级别的 # 严重错误信息

猜你喜欢

转载自blog.csdn.net/zeroooorez/article/details/89944379