模塊: 一個py文件就是一個模塊python
模塊分類:算法
1:內置模塊,登陸模塊,時間模塊,sys模塊,os模塊等等數據庫
2: 擴展模塊,json
3:自定義模塊,本身寫的py文件安全
python 開發效率之高:python的模塊很是多, 第三方庫服務器
序列化模塊網絡
序列化:創造一個序列 ------>特殊處理(序列化)的字符串運維
序列化又分爲3個ide
1,工具
json適用於不一樣語言之間的 ,, 它有四個功能: dumps,loads,dump,load, 四個功能成對存在
json: 數據經過網絡發送給別人 寫入文件也用到 json
被 json序列化的字符串:
①能夠直接經過網絡互相傳輸
②能夠在各個語言中通用
import json dic = {'alex':['123','321','阿達']} print(str(dic)) # 基礎數據類型 str 裏面若是有引導就是單引號 ret = json.dumps(dic) #換成了雙引號 json的str類型 特殊的 print(ret,type(ret))
import json li = ['張三','王五','老土'] f = open('haha',encoding = 'utf-8',mode = 'w') json.dump(li,f) ##將序列化的字符串存儲到文件中, 寫進文件後是 bytes類型 f.close
import json li = ['老二','老三','老四'] f = open('xixi',encoding = 'utf-8') ret = json.load(f) # 讀出了內容 print(ret) f.close()
import json (把多個序列化的字符串寫入到同一個文件中) dic = {"alex":('women','women','老女人')} dic2 = {"alex1":('women','women','老女人')} dic3 = {"alex2":('women','women','老女人')} with open('json_files',encoding = 'utf-8',mode = 'a') as f1: s1 = json.dumps(dic,ensure_ascii = False) #後面的ensure 是須要加的 f1.write(s1+'\n') s2 = json.dumps(dic2,ensure_ascii = False) f1.write(s2+'\n') s3 =json.dumps(dic3,ensure_ascii = False) f1.write(s3 +'\n') 把上面的三個字典 加入到一個文件裏面 with open('json_files',encoding = 'utf-8') as f2: for line in f2: dic = json.loads(line) print(dic,type(dic)) ##把裏面的內容打印出來, 並判斷類型
import json data = {'username':['李華','二愣子'],'sex':'male','age':16} json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False) print(json_dic2)
獲得結果: ##sort_keys 排序 indent:縮進 , separators以什麼分開,鍵值對以什麼分開
{
"age":16,
"sex":"male",
"username":[
"李華",
"二愣子"
]
}
Serialize obj to a JSON formatted str.(字符串表示的json對象) Skipkeys:默認值是False,若是dict的keys內的數據不是python的基本類型(str,unicode,int,long,float,bool,None),設置爲False時,就會報TypeError的錯誤。此時設置成True,則會跳過這類key ensure_ascii:,當它爲True的時候,全部非ASCII碼字符顯示爲\uXXXX序列,只需在dump時將ensure_ascii設置爲False便可,此時存入json的中文便可正常顯示。) If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). indent:應該是一個非負的整型,若是是0就是頂格分行顯示,若是爲空就是一行最緊湊顯示,不然會換行且按照indent的數值顯示前面的空白分行顯示,這樣打印出來的json數據也叫pretty-printed json separators:分隔符,其實是(item_separator, dict_separator)的一個元組,默認的就是(‘,’,’:’);這表示dictionary內keys之間用「,」隔開,而KEY和value之間用「:」隔開。 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. sort_keys:將數據根據keys的值進行排序。 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
2,
pickle 只用於python語言之間的, 可支持python全部的數據類型
缺點: 只能在Python語言中進行數據傳輸.
序列化模塊,python語言網絡交互使用的,他支持全部的python數據類型
也是有四個方法 和json同樣:
dumps,loads, 用於網絡傳輸,多個數據讀寫一個文件
import pickle
dic1 = {'name':'alex'}
s1 = pickle.dumps(dic1) 序列化過程
dic = pickle.loads(s1) 反序列化過程
dump,load 文件操做,(單個數據讀寫一個文件)
多個數據讀寫一個文件的應用:
代碼 02 序列化模塊.py中
循環,try....
import pickle dic = {"alex": ('women','women','老女人')} dic2 = {"alex1": ('women','women','老女人')} dic3 = {"alex2": ('women','women','老女人')} with open('pickle_files',mode = 'wb') as f1: pickle.dump(dic,f1) pickle.dump(dic2,f1) pickle.dump(dic3,f1) 把上面字典加入到了文件夾裏, 反正是看不懂的那種 with open('pickle_files',mode = 'rb') as f2: while True: try: print(pickle.load(f2)) except EOFError: break 把裏面的東西打印出來, 原本是一個一個往外打,這樣寫, 假如裏面有3個 打印第4個不會報錯,break結束
3,
shelve 只是python 小工具(文件方面) 能夠了解一下
import shelve f = shelve.open('shelve_file') f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接對文件句柄操做,就能夠存入數據 f.close() import shelve f1 = shelve.open('shelve_file') existing = f1['key'] #取出數據的時候也只須要直接用key獲取便可,可是若是key不存在會報錯 f1.close() print(existing)
hashlib模塊
1,是一對算法的合集,它包含不少算法,(加密的)
2,hashlib的過程就是將字符串轉化成數字的過程
3,hashlib 對相同的字符串轉化成的數字相同
4,不一樣的電腦對相同的字符串進行加密,轉換成的數字相同.
那麼用在哪裏呢????
密文(密碼)
將密碼用算法加密放置到數據庫,每次取出驗證
文件校驗.
初識 hashlib
① md5 加密算法 經常使用算法,能夠知足通常的經常使用需求
② sha 加密算法 級別高一些, 數字越大級別越高,加密的效率越低,越安全
md5:
s1 = '12345325' ret = hashlib.md5() # 建立一個md5對象 ret.update(s1.encode('utf-8')) #調用此update方法對參數進行加密 是byte類型 print(ret.hexdigest()) #獲得加密後的結果, 定長(長度都同樣) s2 = 'alex12fdsl,.afjsdl;fjksdal;fkdsal;fld;lsdkflas;dkfsda;3' ret = hashlib.md5() #建立一個md5對象 ret.update(s2.encode('utf-8')) #調用此update方法對參數進行加密 byte類型 print(ret.hexdigest()) #獲得加密後的結果 定長
不管字符串多長,返回都是定長的數字
同一字符串,md5值相同
可是呢,總有一些閒人去試你的密碼, 也叫撞庫,由於撞庫,因此相對不安全,如何解決呢?
須要加鹽
s3 = '123456' ret = hashlib.md5('@$1*(^&@^2wqe'.encode('utf-8')) #建立一個md5對象,加鹽 ret.update(s3.encode('utf-8')) #調用此update方法對參數進行加密 byte類型 print(ret.hexdigest()) #獲得加密後的結果. 定長 若是黑客盜取到你的固定鹽'@$1*(^&@^2wqe'內容 那就變成隨機的鹽: username = '爽妹' password = '123456' ret = hashlib.md5(username[::1].encode('utf-8')) ret.update(password.encode('utf-8')) print(ret.hexdigest())
sha 系列
hashlib.shal() #shal與md5 級別相同 可是shal比md5 更安全一些
ret = hashlib.shal()
ret.update('123456'.encode('utf-8'))
print(ret.hexdigest()) #7c4a8d09ca3762af61e59520943dc26494f8941b
ret = hashlib.sha512() # 級別最高 效率低,安全性最大
ret.update('123456'.encode'utf-8')
print(ret.hexdigest()) ##獲得的結果很長很長
文件校驗
對於小文件能夠,可是超大的文件內存受不了,
def func(file_name): with open(file_name,mode = 'rb') as f1: ret = hashlib.md5() ret.update(f1.read()) return ret.hexdigest() print(func('hashlib_file')) print(func('hashlib_file1')) s1 = 'I am 旭哥, 都別惹我.... 不服你試試' ret = hashlib.md5() ret.update(s1.encode('utf-8')) print(ret.hexdigest()) # 15f614e4f03312320cc5cf83c8b2706f s1 = 'I am 旭哥, 都別惹我.... 不服你試試' ret = hashlib.md5() ret.update('I am'.encode('utf-8')) ret.update(' 旭哥, '.encode('utf-8')) ret.update('都別惹我....'.encode('utf-8')) ret.update(' 不服你試試'.encode('utf-8')) print(ret.hexdigest()) # 15f614e4f03312320cc5cf83c8b2706f def func(file_name): with open(file_name,mode='rb') as f1: ret = hashlib.md5() while True: content = f1.read(1024) if content: ret.update(content) else: break return ret.hexdigest() print(func('hashlib_file')) print(func('hashlib_file1'))
hashlib 用在密文,或者文件的校驗
md5: 普通的,加鹽的,動態加鹽的
sha: 普通的,加鹽的,動態加鹽的
文件的校驗: 小文件,大文件
configparser 模塊
幫助你操做(建立,增,刪,改,查)一個配置文件 建立一個文件. import configparser config = configparser.ConfigParser()# config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} # 順序:建立一個對象,而後將文件讀到內存中,在進行相應的操做. # # print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] # # #爲何沒有 DEFAULT,它是特殊的,能夠看作成一個全局的. # print('111' 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> 可迭代對象 # print(config['bitbucket.org']['forwardx11']) #<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 # 增刪改 # import configparser # # config = configparser.ConfigParser() # # config.read('new2.ini') # # config.add_section('日天') # 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 模塊
log 日誌:
何時用到日誌?
生活中:
1, 公司員工信息工號等等須要日誌.
2, 淘寶,京東 你的消費信息,瀏覽記錄等等都記錄日誌中,個性化推薦.
3, 頭條個性化設置(愛好記錄的日誌中).
工做上:
運維人員,任何員工對服務器作過的任何操做,都會記錄到日誌中.
若是你要是從事運維開發的工做,各處都須要日誌.
debug模式,須要依靠日誌的.
定時收集信息,也要記錄日誌.
logging 模塊是輔助你記錄日誌的,不是自動記錄日誌的.
低配版,logging
高配版,logger 對象
低配版::
import logging 等級是一層一層升高的. logging.basicConfig(level=logging.ERROR) # level=logging.DEBUG 設置顯示報錯的級別. logging.debug('debug message') # 調試信息 logging.info('info message') # 正常信息 logging.warning('warning message') # 警告信息:代碼雖然不報錯,可是警告你寫的不規範,必須改. logging.error('error message') # 錯誤信息. logging.critical('critical message') # 嚴重錯誤信息. 用法實例: try: num = input('>>>請輸入') num = int(num) except ValueError: logging.error('出現了 %s' % ValueError) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s', ) # level=logging.DEBUG 設置顯示報錯的級別. logging.debug('debug message') # 調試信息 logging.info('info message') # 正常信息 logging.warning('warning message') # 警告信息:代碼雖然不報錯,可是警告你寫的不規範,必須改. logging.error('error message') # 錯誤信息. logging.critical('critical message') # 嚴重錯誤信息. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s', # datefmt='%a, %d %b %Y %H:%M:%S', # 設置時間格式 filename='low_logging.log', # filemode='w', ) logging.warning('warning 警告錯誤!!!!') # 警告信息:代碼雖然不報錯,可是警告你寫的不規範,必須改. logging.error('error message') # 錯誤信息. logging.critical('critical message') # 嚴重錯誤信息. level=logging.DEBUG 設置顯示報錯的級別. try: num = input('>>>請輸入') num = int(num) except Exception as e: logging.warning(e) # 警告信息:代碼雖然不報錯,可是警告你寫的不規範,必須改. logging.error(e) # 錯誤信息. logging.critical(e) # 嚴重錯誤信息.
low logging 缺點:# 1,寫入文件 打印日誌不能同時進行.# 2 ,寫入文件時文件編碼方式爲gbk..