1. # hash: 算法, 结果是什么? 是内存地址,
  2. # print(hash('123'))
  3. # dic = {'name':'alex'}
  4. # print(hash('name'))
  5. # print(id('name'))
  6.  
  7. # hashlib 模块 与加密相关,被称作 摘要算法.
  8.  
  9. # 1,是一堆算法的合集,他包含很多算法(加密的).
  10. # 2,hashlib的过程就是将字符串转化成---->数字的过程.
  11. # 3,hashlib对相同的字符串转化成的数字相同.
  12. # 4,不同的电脑,对相同的字符串进行 加密 转化成的数字相同.
  13.  
  14. # 用在哪里?
  15. # 密文(密码).
  16. # 将密码用算法加密放置到数据库,每次取出验证.
  17. # 文件的校验.
  18.  
  19. # 初识 hashlib
  20. # import hashlib
  21. #md5 加密算法 常用算法, 可以满足一般的常用的需求
  22. #sha 加密算法 级别高一些, 数字越大级别越高,加密的效率越低,越安全.
  1. #md5
  2. # s1 = '12343254'
  3. # ret = hashlib.md5() # 创建一个md5对象
  4. # ret.update(s1.encode('utf-8')) # 调用此update方法对参数进行加密 bytes类型
  5. # print(ret.hexdigest()) # 得到加密后的结果 定长
  6.  
  7. # 无论字符串多长,返回都是定长的数字,
  8. # 同一字符串,MD5值相同.
  9.  
  10. # 解决方式:加盐.
  11. # s3 = '123456'
  12. # ret = hashlib.md5('aqwe'.encode('utf-8')) # 创建一个md5对象,加盐
  13. # ret.update(s3.encode('utf-8')) # 调用此update方法对参数进行加密 bytes类型
  14. # print(ret.hexdigest()) # 得到加密后的结果 定长 c5f8f2288cec341a64b0236649ea0c37

  15. # 随机的盐:
  16. # username = '爽妹'
  17. # password = '123456'
  18. # ret = hashlib.md5(username[::-1].encode('utf-8'))
  19. # ret.update(password.encode('utf-8'))
  20. # print(ret.hexdigest())
  1. #sha 系列
  2. # hashlib.sha1() # sha1 与md5 级别相同,但是sha1比md5 更安全一些,
  3. # ret = hashlib.sha1()
  4. # ret.update('123456'.encode('utf-8'))
  5. # print(ret.hexdigest()) # 7c4a8d09ca3762af61e59520943dc26494f8941b
    sha也有加盐,动态加盐
  1. # 文件的校验
  2. # 对于小文件可以,但是超大的文件内存受不了,(下面具体代码解决)
  3. # def func(file_name):
  4. # with open(file_name,mode='rb') as f1:
  5. # ret = hashlib.md5()
  6. # ret.update(f1.read())
  7. # return ret.hexdigest()
  8. #
  9. # print(func('hashlib_file'))
  10. # print(func('hashlib_file1'))
  11.  
  12. # def func(file_name):
  13. # with open(file_name,mode='rb') as f1:
  14. # ret = hashlib.md5()
  15. # while True:
  16. # content = f1.read(1024)
  17. # if content:
  18. # ret.update(content)
  19. # else:
  20. # break
  21. # return ret.hexdigest()
  22. # print(func('hashlib_file'))
  23. # print(func('hashlib_file1'))
  1. 大文件可以拆开读,加密结果一样
    # s1 = 'I am 旭哥, 都别惹我.... 不服你试试'
  2. # ret = hashlib.md5()
  3. # ret.update(s1.encode('utf-8'))
  4. # print(ret.hexdigest()) # 15f614e4f03312320cc5cf83c8b2706f
  5.  
  6. # s1 = 'I am 旭哥, 都别惹我.... 不服你试试'
  7. # ret = hashlib.md5()
  8. # ret.update('I am'.encode('utf-8'))
  9. # ret.update(' 旭哥, '.encode('utf-8'))
  10. # ret.update('都别惹我....'.encode('utf-8'))
  11. # ret.update(' 不服你试试'.encode('utf-8'))
  12. # print(ret.hexdigest()) # 15f614e4f03312320cc5cf83c8b2706f

configparser模块

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

创建文件

来看一个好多软件的常见文档格式如下:

  1. [DEFAULT]
  2. ServerAliveInterval = 45
  3. Compression = yes
  4. CompressionLevel = 9
  5. ForwardX11 = yes
  6.  
  7. [bitbucket.org]
  8. User = hg
  9.  
  10. [topsecret.server.com]
  11. Port = 50022
  12. ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. config["DEFAULT"] = {'ServerAliveInterval': '45',
  6. 'Compression': 'yes',
  7. 'CompressionLevel': '9',
  8. 'ForwardX11':'yes'
  9. }
  10.  
  11. config['bitbucket.org'] = {'User':'hg'}
  12.  
  13. config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
  14.  
  15. with open('example.ini', 'w') as configfile:
  16.  
  17. config.write(configfile)

查找文件

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. #---------------------------查找文件内容,基于字典的形式
  6.  
  7. print(config.sections()) # []
  8. # 创建一个对象,然后将文件读到内存中,再进行相应的操作。
  9. config.read('example.ini')
  10. print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']

  11. DEFAULT 比较特殊,可以看做是全局的

    判断节名是否在配置文件中:
  12. print('bytebong.com' in config) # False
  13. print('bitbucket.org' in config) # True
  14.  
  15. 对配置文件中的节对应的项取值:
  16. print(config['bitbucket.org']["user"]) # hg
  17. print(config['DEFAULT']['Compression']) #yes
  18. print(config['topsecret.server.com']['ForwardX11']) #no
  19.  
  20. print(config['bitbucket.org']) #<Section: bitbucket.org> #可迭代对象
  21.  
  22. for key in config['bitbucket.org']: # 注意,有default会默认default的键
  23. print(key)
    结果:
  1.   # user
      # serveraliveinterval
      # compression
      # compressionlevel
      # forwardx11

  1. print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键
    ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
  1. print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对
    [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
  1. print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value

增删改操作

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4.  
  5. config.read('example.ini')
  6.  
  7. config.add_section('yuan')
  8.  
  9. config.remove_section('bitbucket.org')
  10. config.remove_option('topsecret.server.com',"forwardx11")
  11.  
  12. config.set('topsecret.server.com','k1','11111')
  13. config.set('yuan','k2','22222')
  14.  
  15. config.write(open('new2.ini', "w"))

五,logging模块

函数式简单配置

  1. import logging
  2. logging.debug('debug message')
  3. logging.info('info message')
  4. logging.warning('warning message')
  5. logging.error('error message')
  6. logging.critical('critical message')

默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

灵活配置日志级别,日志格式,输出位置:

 
 低配版:    不能写入文件与显示同时进行
  1. import logging
  2. logging.basicConfig(level=logging.DEBUG,
  3. format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  4. datefmt='%a, %d %b %Y %H:%M:%S',
  5. filename='/tmp/test.log',
  6. filemode='w')
  7.  
  8. logging.debug('debug message')
  9. logging.info('info message')
  10. logging.warning('warning message')
  11. logging.error('error message')
  12. logging.critical('critical message')
  1. logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
  2.  
  3. filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
  4. filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
  5. format:指定handler使用的日志显示格式。
  6. datefmt:指定日期时间格式。
  7. level:设置rootlogger(后边会讲解具体概念)的日志级别
  8. stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),
    默认为sys.stderr。若同时列出了filenamestream两个参数,则stream参数会被忽略。
  9.  
  10. format参数中可能用到的格式化串:
  11. %(name)s Logger的名字
  12. %(levelno)s 数字形式的日志级别
  13. %(levelname)s 文本形式的日志级别
  14. %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  15. %(filename)s 调用日志输出函数的模块的文件名
  16. %(module)s 调用日志输出函数的模块名
  17. %(funcName)s 调用日志输出函数的函数名
  18. %(lineno)d 调用日志输出函数的语句所在的代码行
  19. %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  20. %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
  21. %(asctime)s 字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  22. %(thread)d 线程ID。可能没有
  23. %(threadName)s 线程名。可能没有
  24. %(process)d 进程ID。可能没有
  25. %(message)s用户输出的消息

logger对象配置

  1. # 高配版
    # 第一版:只输入文件中.
    # import logging
    # logger = logging.getLogger() # 创建logger对象.
    # fh = logging.FileHandler('高配版logging.log',encoding='utf-8') # 创建文件句柄
    #
    # logger.addHandler(fh) #写入文件
    #
    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning('warning message')
    # logging.error('error message')
    # logging.critical('critical message')

    # 第二版:文件和屏幕都存在.
    # import logging
    # logger = logging.getLogger() # 创建logger对象.
    # fh = logging.FileHandler('高配版logging.log',encoding='utf-8') # 创建文件句柄
    # sh = logging.StreamHandler() #产生了一个屏幕句柄
    #
    # logger.addHandler(fh) #写入文件
    # logger.addHandler(sh) #屏幕显示
    #
    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning('warning message')
    # logging.error('error message')
    # logging.critical('critical message')

    # 第三版:文件和屏幕都存在的基础上 设置显示格式.
    # import logging
    # logger = logging.getLogger() # 创建logger对象.
    # fh = logging.FileHandler('高配版logging.log',encoding='utf-8') # 创建文件句柄
    # sh = logging.StreamHandler() #产生了一个屏幕句柄
    # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    #
    # logger.addHandler(fh) #添加文件句柄
    # logger.addHandler(sh) #添加屏幕句柄
    # sh.setFormatter(formatter) # 设置屏幕格式
    # fh.setFormatter(formatter) # 设置文件的格式 (这两个按照需求可以单独设置)
    #
    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning('warning message')
    # logging.error('error message')
    # logging.critical('critical message')

    #第四版 文件和屏幕都存在的基础上 设置显示格式.并且设置日志水平.
    # import logging
    # logger = logging.getLogger() # 创建logger对象.
    # fh = logging.FileHandler('高配版logging.log',encoding='utf-8') # 创建文件句柄
    # sh = logging.StreamHandler() #产生了一个屏幕句柄
    # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    # logger.setLevel(logging.DEBUG) #设置总开关,总开关不写,默认从Warning开始
    # #如果你对logger对象设置日志等级.那么文件和屏幕都设置了.
    # #如果想设置分开关:必须要从比总开关更高级的开始
    # #文件开关和屏幕开关可以分开设置
    #
    # logger.addHandler(fh) #添加文件句柄
    # logger.addHandler(sh) #添加屏幕句柄
    # sh.setFormatter(formatter) # 设置屏幕格式
    # fh.setFormatter(formatter) # 设置文件的格式 (这两个按照需求可以单独设置)
    # fh.setLevel(logging.DEBUG) #设置文件开关
    # sh.setLevel(logging.DEBUG) #设置屏幕开关

    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning('warning message')
    # logging.error('error message')
    # logging.critical('critical message')
  1. # 调用系统的日志信息
  2.  
  3. import traceback
  4.  
  5. def func():
  6. print(1/0)
  7.  
  8. try:
  9. func()
  10. except Exception as e:
  11. logger1.error(traceback.format_exc()) # 错误信息记录到日志

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

fh.setLevel(logging.Debug)单对文件流设置某个级别。

hashlib,configparser,logging的更多相关文章

  1. python---基础知识回顾(四)(模块sys,os,random,hashlib,re,序列化json和pickle,xml,shutil,configparser,logging,datetime和time,其他)

    前提:dir,__all__,help,__doc__,__file__ dir:可以用来查看模块中的所有特性(函数,类,变量等) >>> import copy >>& ...

  2. python模块基础之json,requeste,xml,configparser,logging,subprocess,shutil。

    1.json模块 json     用于[字符串]和 [python基本数据类型] 间进行转换(可用于不同语言之前转换),json.loads,将字符串转成python的基本数据类型,json.dum ...

  3. python成长之路第三篇(4)_作用域,递归,模块,内置模块(os,ConfigParser,hashlib),with文件操作

    打个广告欢迎加入linux,python资源分享群群号:478616847 目录: 1.作用域 2.递归 3.模块介绍 4.内置模块-OS 5.内置模块-ConfigParser 6.内置模块-has ...

  4. python 闭包,装饰器,random,os,sys,shutil,shelve,ConfigParser,hashlib模块

    闭包 def make_arerage(): l1 = [] def average(price): l1.append(price) total = sum(l1) return total/len ...

  5. python之hashlib、configparser、logging模块

    hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数 ...

  6. 模块2 hashlib;configparser; logging;

    hashlib模块: hashlib模块提供了提供了常用的摘要算法,例如MD5,SHA1等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据 ...

  7. hashlib模块configparser模块logging模块

    hashlib模块 算法介绍 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长 ...

  8. 常用模块二(hashlib、configparser、logging)

    阅读目录 常用模块二 hashlib模块 configparse模块 logging模块   常用模块二 返回顶部 hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SH ...

  9. collections、random、hashlib、configparser、logging模块

    collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...

  10. 常用模块(collections模块,时间模块,random模块,os模块,sys模块,序列化模块,re模块,hashlib模块,configparser模块,logging模块)

    认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...

随机推荐

  1. 这一次,彻底理解XSS攻击

    希望读完本文大家彻底理解XSS攻击,如果读完本文还不清楚,我请你吃饭慢慢告诉你~ 话不多说,我们进入正题. 一.简述 跨站脚本(Cross-site scripting,简称为:CSS, 但这会与层叠 ...

  2. centos7中redis安装配置

    1.官网下载对应版本,本例以5.0.5为例 2.tar -zxvf xxxxx 并mv到安装目录 3.进入redis-5.0.5目录下,执行编译命令 make 4.编译完成后,经redis安装到指定目 ...

  3. dalao高精

    #ifndef MY_BIGN_H#define MY_BIGN_H 1#pragma GCC system_header#include<cstring>#include<algo ...

  4. 备战金三银四!一线互联网公司java岗面试题整理:Java基础+多线程+集合+JVM合集!

    前言 回首来看2020年,真的是印象中过的最快的一年了,真的是时间过的飞快,还没反应过来年就夸完了,相信大家也已经开始上班了!俗话说新年新气象,马上就要到了一年之中最重要的金三银四,之前一直有粉丝要求 ...

  5. String被final修饰

    源码:

  6. netty核心组件之channel、handler、ChannelHandlerContext、pipeline

    channel介绍: netty中channel分为NioServerScoketChannel和NioSocketChannel,分别对应java nio中的ServerScoketChannel和 ...

  7. Qt开发的应用记录读取用户习惯设置的方法

    Qt开发的应用记录读取用户习惯设置的方法 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/w ...

  8. 【十天自制软渲染器】DAY 01:图形学学习建议与环境搭建

    推荐直接阅读博客原文,更新更及时,阅读体验更佳 「十天自制软渲染器」这个标题我承认标题党了.在对图形学一无所知的情况下想十天自制一个软渲染器,就好似一节课没上过却试图一个晚上看完<30 天精通 ...

  9. 【MySQL 基础】MySQL必知必会

    MySQL必知必会 简介 <MySQL必知必会>的学习笔记和总结. 书籍链接 了解SQL 数据库基础 什么是数据库 数据库(database):保存有组织的数据的容器(通常是一个文 件或一 ...

  10. docker 数据卷的挂载和使用

    容器之间的数据共享技术, Docker容器产生的数据同步到本地 卷技术 --> 目录挂载, 将容器内的目录挂载到服务器上 使用命令来挂载 -v # 可以挂载多个目录 docker run -it ...