一、常用子產品二
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)單對檔案流設定某個級别。
轉載于:https://www.cnblogs.com/haiyan123/p/7382604.html