python常用模組二

  • 2019 年 10 月 6 日
  • 筆記

hashilib模組

我們的登錄密碼在資料庫中不能存明文,當別人拿到資料庫,看到帳號密碼是很恐怖的事情。所以我們就需要hashilib模組來加密。前幾年csdn的資料庫外泄,而且存的是明文,就很麻煩,所幸並不沒有涉及大量¥。

# 導入模組

import hashlib

# 實例化md5演算法,不可逆,所謂破解都是撞庫。對於同一個字元串,進行md5計算,得到的值是一樣的。那麼我們存入資料庫的時候加密,在驗證登錄時,密碼也進行加密對比即可。

md5 = hashlib.md5()

# 加密 bytes類型

md5.update(b'123456')

# 取出來

print(md5.hexdigest())

在hashlib中還有其他加密,sha等演算法。使用方法一致,除了實例化的時候不一樣,其他一致。

sha有很多種,有的計算的短,有的計算的長,越長越安全,但是時間成本越高。

hashlib不僅僅可以對密碼進行加密,根據加密的特性,比如我們用qq傳文件,在傳送完成的時候,用md5加密,對比兩個md5是否一致,一致說明文件是相同的。md5不僅可以對字元串進行加密,也可以對文件等進行加密。以此來檢驗文件的一致性。

為防止撞庫:

import hashlib

# 這裡的jiami叫做加鹽。

md5 = hashlib.md5(bytes('jiami',encoding='utf-8'))

md5.update(b'123456')

print(md5.hexdigest())

# 動態加鹽

使用用戶名的一部分或者用戶名的一部分再拼接一個字元串的方式作為鹽。

configparser模組

處理配置文件的模組。

# 導入模組

import configparser

# 實例化

config =configparser.ConfigParser()

# 定義配置文件的內容

config['DEFAULT'] = {

'author':'張三',

'age':'18',

'sex':'男'

}

config['path'] = {

'path1':'D:/python'

}

# 寫入配置文件

with open('config.ini','w') as configfile:

config.write(configfile)

就會是個生成一個config.ini的文件,內容為:

[DEFAULT]

author = 張三

age = 18

sex = 男

[path]

path1 = D:/python

[DEFAULT]和[path]叫做組,以分組的形式來寫配置文件。

其他操作:

read(filename) # 讀取配置文件,直接讀取ini文件內容

sections() # 獲取ini文件內所有的組,以列表形式返回,除了DEFAULT

options(sections) # 獲取指定組下所有options ,以列表形式返回

items(sections) # 獲取指定組下所有的鍵值對

get(section, option) # 獲取組中option的值,返回為string類型

實例:

import configparser

config =configparser.ConfigParser()

# 讀取配置文件

config.read('config.ini')

# 輸出所有組的組名,這裡輸出['path'],['DEFAULT']很特殊,不會顯示

print(config.sections())

# 輸出一個組下的名字 輸出['path1', 'author', 'age', 'sex']會把默認的也輸出

print(config.options('path'))

# 輸出[('author', '張三'), ('age', '18'), ('sex', '男'), ('path1', 'D:/python')]

print(config.items('path'))

# 輸出D:/python

print(config.get('path', 'path1'))

# 判斷一個組是否在其中

print('path' in config) # True

# 其他取值方式

print(config['path']['path1']) # D:/python

# 也可以循環一個組

for key in config['path']:

print(key)

# 添加一個組

config.add_section('name')

# 添加一個組的配置

config.set('path','path1','123456')

# 添加一個配置

config.set('name','name1','李四')

# 刪除一個組

config.remove_section('path')

# 刪除一個組中的某個配置

config.remove_option('path','path1')

# 最後都需要寫入

config.write(open('config.ini',w))

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

只輸出了上面三個,列印是有級別的,從小到下,依次由低級別到高級別

DEBUG:排錯資訊

INFO:正常資訊

WARNING:表示警告

error:表示錯誤

CRITICAL:嚴重錯誤

程式默認是從WARNING開始輸出的。

配置日誌級別,格式,輸出

import logging

logging.basicConfig(level = logging.DEBUG,

format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s – %(message)s',

datefmt = '%a, %d %b %H:%M:%S',

filename = 'test.log',

filemode = 'w'

)

logging.debug('debug message')

logging.info('info message')

logging.warning('warning message')

logging.error('error message')

logging.critical('critical message')

生成一個test.log文件:

Sun, 18 Nov 14:05:25 Demo.py[line:249] DEBUG – debug message

Sun, 18 Nov 14:05:25 Demo.py[line:250] INFO – info message

Sun, 18 Nov 14:05:25 Demo.py[line:251] WARNING – warning message

Sun, 18 Nov 14:05:25 Demo.py[line:252] ERROR – error message

Sun, 18 Nov 14:05:25 Demo.py[line:253] CRITICAL – critical message

level:指定輸出的級別,我們這裡選擇的DEBUG,為最小的級別,所以都輸出了

format:格式化輸出

%(levelno)s:列印日誌級別的數值

%(levelname)s:列印日誌級別的名稱

%(pathname)s:列印當前執行程式的路徑,其實就是sys.argv[0]

%(filename)s:列印當前執行程式名

%(funcName)s:列印日誌的當前函數

%(lineno)d:列印日誌的當前行號

%(asctime)s:列印日誌的時間

%(thread)d:列印執行緒ID

%(threadName)s:列印執行緒名稱

%(process)d:列印進程ID

%(message)s:列印日誌資訊

datefmt:時間的格式

filename:文件的名字

filemode:文件打開方式

用自帶的方法有很多局限性:比如用自帶的寫入的日誌文件為中文會亂碼,不能同時輸出到文件和螢幕,我們自己來寫一下。

實例:

import logging

# 創建一個對象

logger = logging.getLogger()

# 創建一個文件操作

fh = logging.FileHandler('test.log',encoding='utf-8')

# 創建一個螢幕輸出

sh = logging.StreamHandler()

# 添加到文件的級別

logger.setLevel(logging.DEBUG)

# 輸出到螢幕的級別

logger.setLevel(logging.DEBUG)

# 定義一個格式

format = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s – %(message)s')

# 格式作用於文件

fh.setFormatter(format)

# 格式作用於螢幕輸出

sh.setFormatter(format)

# 文件作用於對象

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

文件和螢幕都會輸出:

2018-11-18 14:48:38,059 Demo.py[line:274] DEBUG – debug message

2018-11-18 14:48:38,060 Demo.py[line:275] INFO – info message

2018-11-18 14:48:38,060 Demo.py[line:276] WARNING – warning message

2018-11-18 14:48:38,060 Demo.py[line:277] ERROR – error message

2018-11-18 14:48:38,060 Demo.py[line:278] CRITICAL – critical message