python全棧開發【第十一篇】Python常用模塊三(hashlib,configparser,logging)
hashlib模塊
hashlib提供了常見的摘要算法,如md5和sha1等等。
那麽什麽是摘要算法呢?摘要算法又稱為哈希算法、散列算法。它通過一個函數,把任意長度的數據轉換為一個長度固定的數據串(通常用16進制的字符串表示)。
註意:摘要算法不是一個解密算法。(摘要算法,檢測一個字符串是否發生了變化)
應塗:1.做文件校驗
2.登錄密碼
密碼不能解密,但可以撞庫,用‘加鹽’的方法就可以解決撞庫的問題。所有以後設置密碼的時候要設置的復雜一點。
#用戶密碼 import hashlib # md5_obj = hashlib.md5() 未加鹽 md5_obj = hashlib.md5(‘nezha‘.encode(‘utf-8‘)) #加鹽後(就讓你的密碼更牢固了) md5_obj.update(‘123456‘.encode(‘utf-8‘)) print(md5_obj.hexdigest()) md5_obj.update(‘hello‘.encode(‘utf-8‘)) print(md5_obj.hexdigest()) # ----------- user = ‘haiyan‘ password = ‘123456‘ md5_obj= hashlib.md5(user.encode(‘utf-8‘)) #加鹽(哪怕被人的密碼和你的密碼一樣, # 那你加鹽以後就只有你的用戶名對應的是你的密碼了) md5_obj.update(password.encode(‘utf-8‘)) print(md5_obj.hexdigest())
#文件一致性校驗(檢測文件改變了沒) import hashlib md5_obj = hashlib.md5() import os filesize = os.path.getsize(‘filename‘) #文件大小 f = open(‘filename‘,‘rb‘) while filesize>0: if filesize > 1024: content = f.read(1024) filesize -= 1024 else: content = f.read(filesize) filesize -= filesize md5_obj.update(content) # for line in f: # md5_obj.update(line.encode(‘utf-8‘)) md5_obj.hexdigest()
configparser模塊
該模塊適用於配置文件的格式與windows ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。
1.創建文件
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘, ‘ForwardX11‘:‘yes‘ } config[‘bitbuck et.org‘] = {‘User‘:‘hg‘} config[‘topsecret.server.com‘] = {‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘} with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)
2.查找文件
import configparser config = configparser.ConfigParser() # print(config.sections()) config.read(‘example.ini‘) print(config.sections()) #讀出來的是文件裏面的組, # 而且裏面的[DEFAULT]組沒有顯示出來 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
3.增刪改操作
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"))
logging模塊
函數式簡單配置
默認情況下Python的logging模塊將日誌打印到了標準輸出中,且只顯示了大於等於WARNING級別的日誌,這說明默認的日誌級別設置為WARNING(日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG),默認的日誌格式為日誌級別:Logger名稱:用戶輸出消息。
只顯示大於等於warning基本的日誌,這說明默認的日誌級別設置為warning (日誌級別等級critical>error>warning>info>debug) import logging logging.debug(‘debug message‘) logging.info(‘info message‘) logging.warning(‘warning message‘) #warning 警告(從警告開始才執行) logging.error(‘error message‘) #error 錯誤 logging.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用戶輸出的消息
有兩種方式去應用logging模塊
1.設置config
import logging logging.basicConfig( level=logging.DEBUG , #多輸出一些細節 # level = logging.WARNING #就不用輸出那些細節了 format = ‘%(name)s %(asctime)s [%(lineno)d] ---%(message)s‘, #本身就存在在python語法中,拿過來用就行了 # level和format也是不能變的,它是參數,不是變量 # %(lineno)d指定代碼塊的行 # %(name)s當前管理員的用戶 datefmt = ‘%d/%m/%Y %H:%M:%S‘,#指定日期時間格式 filename = ‘logging_info‘ #自動創建了一個文件,並且把日誌寫到了文件裏 ) logging.debug(‘debug message‘) logging.info(‘info message‘) logging.warning(‘warning message‘) logging.error(‘error message‘) logging.critical(‘critical message‘)
2.logger對象配置
可以控制輸入到文件,也可以輸入到屏幕
可以同時在幾個文件中輸出
# logger對象 import logging def mylogger(filename,file=True,stream=True): logger = logging.getLogger() formater = logging.Formatter( fmt=‘%(name)s %(asctime)s [%(lineno)d] ---%(message)s‘, datefmt=‘%d/%m/%Y %H:%M:%S‘ # 時間格式 ) logger.setLevel(logging.DEBUG) #指定日誌打印的等級 if file: file_handler = logging.FileHandler(‘logging.log‘,encoding=‘utf-8‘)# 創建一個handler,用於寫入日誌文件 file_handler.setFormatter(formater) # 文件流,文件操作符 logger.addHandler(file_handler) if stream: stream_handler = logging.StreamHandler() # 再創建一個handler,用於輸出到控制臺 stream_handler.setFormatter(formater) #屏幕流,屏幕操作流 #如果想讓文件流和屏幕流輸出的東西的格式不一樣,那麽就在寫一個 格式formater1,這樣就可以了 logger.addHandler(stream_handler) return logger logger = mylogger(‘logging.log‘,file=False) logger.warning(‘啦啦啦啦‘) logger.debug(‘debug message‘)
ogging庫提供了多個組件:Logger、Handler、Filter、Formatter。Logger對象提供應用程序可直接使用的接口,Handler發送日誌到適當的目的地,Filter提供了過濾日誌信息的方法,Formatter指定日誌顯示格式。另外,可以通過:logger.setLevel(logging.Debug)設置級別,當然,也可以通過
fh.setLevel(logging.Debug)單對文件流設置某個級別。
python全棧開發【第十一篇】Python常用模塊三(hashlib,configparser,logging)