hashlib,configparser,logging模塊


一、常用模塊二

hashlib模塊

hashlib提供了常見的摘要算法,如md5和sha1等等。

那么什么是摘要算法呢?摘要算法又稱為哈希算法、散列算法。它通過一個函數,把任意長度的數據轉換為一個長度固定的數據串(通常用16進制的字符串表示)。

注意:摘要算法不是一個解密算法。(摘要算法,檢測一個字符串是否發生了變化)

應塗:1.做文件校驗

   2.登錄密碼

      密碼不能解密,但可以撞庫,用‘加鹽’的方法就可以解決撞庫的問題。所有以后設置密碼的時候要設置的復雜一點。

 1 import hashlib
 2 # md5_obj = hashlib.md5()  未加鹽
 3 md5_obj = hashlib.md5('nezha'.encode('utf-8')) #加鹽后(就讓你的密碼更牢固了)
 4 md5_obj.update('123456'.encode('utf-8'))
 5 print(md5_obj.hexdigest())
 6 md5_obj.update('hello'.encode('utf-8'))
 7 print(md5_obj.hexdigest())
 8 # -----------
 9 user = 'haiyan'
10 password = '123456'
11 md5_obj= hashlib.md5(user.encode('utf-8'))  #加鹽(哪怕被人的密碼和你的密碼一樣,
12 # 那你加鹽以后就只有你的用戶名對應的是你的密碼了)
13 md5_obj.update(password.encode('utf-8'))
14 print(md5_obj.hexdigest())
用戶密碼
 1 import hashlib
 2 md5_obj = hashlib.md5()
 3 import os
 4 filesize = os.path.getsize('filename')  #文件大小
 5 f = open('filename','rb')
 6 while filesize>0:
 7     if filesize > 1024:
 8         content = f.read(1024)
 9         filesize -= 1024
10     else:
11         content = f.read(filesize)
12         filesize -= filesize
13     md5_obj.update(content)
14 # for line in f:
15 #     md5_obj.update(line.encode('utf-8'))
16 md5_obj.hexdigest()
文件校驗(檢測文件改變了沒)

configparser模塊

該模塊適用於配置文件的格式與windows  ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。

1.創建文件

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

2.查找文件

 1 import configparser
 2 config = configparser.ConfigParser()
 3 # print(config.sections())
 4 config.read('example.ini')
 5 print(config.sections())  #讀出來的是文件里面的組,
 6 # 而且里面的[DEFAULT]組沒有顯示出來
 7 print('bytebong.com' in config) # False
 8 print('bitbucket.org' in config) # True
 9 print(config['bitbucket.org']["user"])  # hg
10 print(config['DEFAULT']['Compression']) #yes
11 print(config['topsecret.server.com']['ForwardX11'])  #no
12 print(config['bitbucket.org'])          #<Section: bitbucket.org>
13 for key in config['bitbucket.org']:     # 注意,有default會默認default的鍵
14     print(key)
15 print(config.options('bitbucket.org'))  # 同for循環,找到'bitbucket.org'下所有鍵
16 print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有鍵值對
17 print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key對應的value
查找文件

3.增刪改操作

1 import configparser
2 config = configparser.ConfigParser()
3 config.read('example.ini')
4 config.add_section('yuan')
5 # config.remove_section('bitbucket.org') #刪除組
6 # config.remove_option('topsecret.server.com',"forwardx11") #刪除組里面的項
7 config.set('topsecret.server.com','k1','11111')
8 config.set('yuan','k2','22222')
9 config.write(open('new2.ini', "w"))
增刪改操作

logging模塊

 函數式簡單配置

默認情況下Python的logging模塊將日志打印到了標准輸出中,且只顯示了大於等於WARNING級別的日志,這說明默認的日志級別設置為WARNING(日志級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG),默認的日志格式為日志級別:Logger名稱:用戶輸出消息。

1 只顯示大於等於warning基本的日志,這說明默認的日志級別設置為warning
2 (日志級別等級critical>error>warning>info>debug)
3 import logging
4 logging.debug('debug message')
5 logging.info('info message')
6 logging.warning('warning message')  #warning 警告(從警告開始才執行)
7 logging.error('error message') #error 錯誤
8 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。若同時列出了filename和stream兩個參數,則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用戶輸出的消息
配置參數

 有兩種方式去應用logging模塊

1.設置config

 1 import logging
 2 logging.basicConfig(
 3     level=logging.DEBUG ,    #多輸出一些細節
 4     # level = logging.WARNING  #就不用輸出那些細節了
 5     format = '%(name)s %(asctime)s [%(lineno)d] ---%(message)s', #本身就存在在python語法中,拿過來用就行了
 6     # level和format也是不能變的,它是參數,不是變量
 7     # %(lineno)d指定代碼塊的行
 8     # %(name)s當前管理員的用戶
 9     datefmt = '%d/%m/%Y %H:%M:%S',#指定日期時間格式
10     filename = 'logging_info' #自動創建了一個文件,並且把日志寫到了文件里
11 
12 )
13 logging.debug('debug message')
14 logging.info('info message')
15 logging.warning('warning message')
16 logging.error('error message')
17 logging.critical('critical message')
設置config

 2.logger對象配置

可以控制輸入到文件,也可以輸入到屏幕

可以同時在幾個文件中輸出

 1 import logging
 2 def mylogger(filename,file=True,stream=True):
 3     logger = logging.getLogger()
 4     formater = logging.Formatter(
 5         fmt='%(name)s %(asctime)s [%(lineno)d] ---%(message)s',
 6         datefmt='%d/%m/%Y %H:%M:%S'  # 時間格式
 7     )
 8     logger.setLevel(logging.DEBUG)  #指定日志打印的等級
 9     if file:
10         file_handler = logging.FileHandler('logging.log',encoding='utf-8')# 創建一個handler,用於寫入日志文件
11         file_handler.setFormatter(formater)  # 文件流,文件操作符
12         logger.addHandler(file_handler)
13     if stream:
14         stream_handler = logging.StreamHandler()  # 再創建一個handler,用於輸出到控制台
15         stream_handler.setFormatter(formater) #屏幕流,屏幕操作流
16         #如果想讓文件流和屏幕流輸出的東西的格式不一樣,那么就在寫一個 格式formater1,這樣就可以了
17         logger.addHandler(stream_handler)
18     return logger
19 logger = mylogger('logging.log',file=False)
20 logger.warning('啦啦啦啦')
21 logger.debug('debug message')
logger對象

logging庫提供了多個組件:Logger、Handler、Filter、Formatter。Logger對象提供應用程序可直接使用的接口,Handler發送日志到適當的目的地,Filter提供了過濾日志信息的方法,Formatter指定日志顯示格式。另外,可以通過:logger.setLevel(logging.Debug)設置級別,當然,也可以通過

fh.setLevel(logging.Debug)單對文件流設置某個級別。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM