經常使用函數
name = '{wh}my \t name is {name},age is {age}.' print(name.capitalize()) # 字符串的開頭字母大寫 print(name.center(100, "+")) # 在字符串兩邊增長'+'號,使整個字符串的個數爲50位置 print(name.endswith(".")) # 判斷是否以X結尾,返回布爾值 print(name.expandtabs(30)) # 補充\t的次數\t按一個空格處理,\t通常爲2個空格,但在字符串開頭或者\n後爲4個空格 print(name.find("n")) # 查找字符串索引,若是不存在返回-1
print(name.rfind("n") # 從右邊倒敘查找字符串索引,如不存在返回-1 print(name.index("n")) # 查找元素,若是不存在報錯 print(name.count("z")) # 查找元素個數,若是不存在返回0 print(name.format(wh="nihao,", name="1233", age=100)) # 格式化字符串
print('{:^10},{:6}'.format('username','password')) #格式化輸出擴展 username對應的:^10是右對齊10個字符後輸出,password對應:6是默認左對齊6個字符後輸出 print(name.format_map({'wh': 'huanying,', 'name': 'xiaoming', "age": "19"})) # 格式化字符串字典形式 print("sadads12313#$".isalnum()) # 是否包含數字和字母 print("123".isalpha()) # 是不是英文 print("abc".isdigit()) # 是不是數字 print(name.decimal()) # 是不是十進制數字 print("#¥&*……&*".isidentifier()) # 是不是一個合法的變量名,不經常使用 print("asdadA".islower()) # 判斷字符串中是否所有小寫 print("name".isupper()) # 判斷字符串中是否所有是大寫 print("@#@$#@QsaddsadS Sad ".istitle()) # 判斷是否首字母大寫,後面小寫,標題樣式 print("___".join([name, "enen", "oo"])) # 拼接字符串 前爲拼接符,後爲拼接字符串,以後變成一個新的字符串 print("SAHD #@OAHDa sd ad".lower()) # 所有變成小寫 print("sahdk".upper()) # 所有變成大寫 print(' \t \nmysql\t\n'.lstrip()) # 去除左邊的換行和空格 print(' \t \nmysql\t\n '.rstrip()) # 去除右邊的換行和空格 print(' \t \nmysql\t\n '.strip()) # 去掉兩邊的換行和空格 print(" kongge ".isspace()) # 判斷是否全是空格 print(" dasds ".split() # 去除兩邊空格並以字典形式返回 print(name.splitlines()) # 以換行符分割字符串
print("mysql is db".replace("mysql", "oracle")) # replace 所有替換 print("mysql is dbisis".rfind("is")) # 返回最右邊字符的下標 print("1+2+3+4".split("+")) # 以+分割字符串,以list形式返回 print("1+2+3+4\n5+6+7+8".splitlines()) # 以換行符字符串,以list形式返回 print("abcABC".swapcase()) # 大小寫所有反轉 print("1".zfill(2)) # 將前面字符串中的位數補充0後面填的位數,結果爲01 print(name.endswith("{age}.")) # 判斷字符串結尾是否一致 返回布爾值 print(name.startswith("{age}.")) # 判斷字符串開頭是否一致 返回布爾值 print(bin(12)) # 獲取整數的二進數形式 print(name.ljust(50, '*')) # 在name的左邊補充50個* name.rjust()爲在右側 str1 = "Runoob example....wow!!!" # maketrans與tranlate的應用 l = "12345" # l 和 r 字符串必須數量相同 r = "abcde" res = str1.maketrans(r, l) # 把r替換爲l在和str1比對,找到相同的並修改 print(str1.translate(res) # 打印結果爲Runoo2 5x1mpl5....wow!!! print(max(name)) # 返回字符串中的最大字母 優先小寫字母 其次大寫字母 其次數字 最後是特殊字符 min()最小
print(bool('')) #布爾值判斷,例子中返回false,非零或者空爲true
print(round(3.1415926,2)) #取小數位數,例子中參數爲2因此返回3.14
print(sorted([1,3,400,234,23],reverse=True)) #返回排序方式按降序排列,去掉revese按順序排列
print(any([1,2,3,45])) #返回布爾值,判斷list中只要有一個非零非空的值就返回True,不然返回false
print(all([1,2,3,45])) #返回布爾值,判斷list中只要有一個零或者空的值就返回False,不然返回True
print(dir(name)) #查詢方法,輸出name的全部方法
print(eval("1+1")) #執行一個字符串表達式,返回計算的結果,如例子中返回2,能夠把執行簡單的python代碼
print(exec("print('nihao')")) #執行python代碼,經常使用於瀏覽器形式的代碼編輯軟件,可是略微不安全
print(list(map(funcion,L))) #循環調用函數,而後保存函數返回值,放到一個list裏,若是不加list返回的是一個生成器
#map的實例
# map(function, iterable, ...) # Python 2.x # 返回列表。 # Python3.x # 返回迭代器。 #map會把iterable裏的值依次放入function執行,返回迭代器 #案例1. def f(x): return x * x l = [1, 2, 3, 4] res = map(f, l) print(list(res)) # [1, 4, 9, 16] #案例2: l = [{'username': 'rainbol'}, {'username': 'Asdads'}, {'username': 'ASIUDHUASOIDH'}] # 假設咱們要把username的值變成爲小寫 def s(x): return x.get('username').lower() print(list(map(s, l)))#['rainbol', 'asdads', 'asiudhuasoidh']
print(reduce(fuc,iter[...])) #序列中元素進行累計html
# reduce(function, iterable[, initializer]) from functools import reduce # py3後將reduce放在functools裏了 # reduce的做用是把list中的值依次拿去fuction裏執行,若是有返回值會拿到返回值和下一個數去執行,直到拿完爲止 # reduce作累加是個不錯的選擇 def fuc4(x, y): print(x, y) return x + y res = reduce(fuc4, [1, 2, 3, 54, 123]) print(res) # 183
print(list(filter(funcion,L))) #過濾,循環調用函數,若是函數返回的值爲真,那麼就保存這個值
print(getattr(對象"函數名)) #獲取一個對象裏面的屬性(方法,變量),若是要使用這個方法就返回值加括號()
print(hasattr(模塊,方法)) #查看模塊下是否有該方法,返回布爾值
print(isintance(對象,類)) #判斷參數1是不是參數2的類或者父類的實例,返回布爾值
數據類型轉換
a = 1234
print(0x4d2) #其餘進制數輸入直接轉成10進制
print(hex(a)) #轉成16進制數
print(oct(a)) #轉成8進制數
print(bin(a)) #轉成2進制數
print('asd'.encode()) #字符串轉成二進制,返回b'asd'; 'asd'.encode()將encode轉換成utf-8編碼
print(b'asd'.decode()) #二進制轉成字符串,decode是bytes類型
print(chr(78)) #0-255內整數做爲參數,返回一個對應的ascii碼值
print(ord('a')) #將一個字符轉換成ascii碼
b = ["1234",23,23,213,21341]
list(b) #轉成列表
tuple(b) #轉成元祖
dist(b) #轉成字典
int(a) #轉成整型
float(a) #轉成浮點型
res1= set(b) #返回一個去重,無序,可變集合
res2 = frozenset(b) #返回一個去重,無序,不可變的集合,二者區別:變量不能點出add和remove方法
b_str = str(b) #str()通常是將數值轉成字符串(返回一個字符串,包含對象的友好的可打印表示形式。對於字符串,它返回字符串自己)
b_repr = repr(b) #repr()是將一個對象轉成字符串顯示
random模塊 import random print(random.sample([1,3,4,5,6],2)) # 返回list中的隨機兩個元素,如位數超出會報錯 print(random.randrange(100)) # 返回一個從0到100之間的整數,包括0,不包括100 print(random.randrange(5,10,2)) # 指定5到10之間並間隔(步長)爲2整數 print(random.randint(1, 3)) # 指定包括1包括3之間的整數 print(random.random()) # 打印0到1之間的隨機浮點數,包括0 print(random.uniform(1.1,32.2)) # 打印一個1.1到32.2之間隨機的浮點數 a = [1,23,4,5,6,7] print(random.choice(a)) # 指定a列表或者是元祖中隨機取一個元素,列表爲空報錯 random.shuffle(a) print(a) # 打亂a列表中的全部元素,注意輸出爲a而不能把它變成一個變量 random.choices(population, weights=None, *, cum_weights=None, k=1) # 3.6版本新增。從population集羣中隨機抽取K個元素(可重複)weights是相對權重列表,cum_weights是累計權重,兩個參數不能同時存在,k表示個數。 random.choices(["紅球","黃球","籃球","黑球"], [50,30,15,5], k=1) string模塊 import string string.ascii_letters # 列出全部大小寫字母 string.ascii_lowercase # 列出全部小寫字母 string.ascii_uppercase # 列出全部大寫字母 string.digits # 列出全部數字 string.punctuation # 列出全部特殊字符 string.printable # 列出全部字符,數字,字母 string.hexdigits # 列出全部16進制數 string.octdigits # 列出全部8進制數 string.whitespace # 列出全部空白符 os模塊 與操做系統進行交互 import os
os.system('ls') os.getcwd() # 獲取當前工做目錄 os.chmod("/local/upload/",7) # 給文件目錄/添加權限 os.chdir("../") # 更改當前目錄 os.curdir() # 當前目錄 os.pardir() # 父目錄 os.makedir("/usr/local/tomcat") # 遞歸建立目錄,父目錄不存在時自動建立 os.removedir("/usr/local/tomcat") # 遞歸刪除空目錄,包括父目錄 os.mkdir("a") # 建立文件夾 os.rmdir("a") # 刪除空文件夾 os.remove("a.txt") # 刪除指定文件
import shutil shutil.rmtree(del_file_dir)#刪除不爲空的文件夾 #https://blog.csdn.net/Tri_C/article/details/99862201
os.listdir() # 列出指定目錄下的全部文件,不傳的話是當前目錄 .爲當前路徑 os.rename("a","b") # 把a重命名成b os.stat("a.py") # 獲取文件信息 print(os.sep) # 當前操做系統的路徑分隔符 print(os.linesep) # 當前操做系統的換行符 print(os.pathsep) # 當前系統的環境變量中每一個路徑的分隔符,linux是:,windows是; print(os.environ) # 當前系統的環境變量 print(os.name) # 當前系統名稱 os.walk("路徑") # 遞歸查詢路徑下的全部文件及文件夾,三個參數 path(當前目錄),dirs(當前目錄的全部文件夾,不包括文件),files(當前目錄的全部文件,不包括文件夾) os.system('操做系統命令') 或者 os.popen('操做系統命令') # 前者只能將命令執行,獲取不到結果,後者能夠,res = os.popen('ipconfig').read() print(os.path.abspath(__file__)) # 獲取絕對路徑/也可使相對路徑變成絕對路徑
print(os.path.relpath('c://')) #絕對路徑轉換成相對路徑 print(os.path.getsize('a.txt')) # 取文件大小,單位是字節 print(os.path.split("/usr/hehe/hehe.txt")) # 分割路徑和文件名 print(os.path.dirname("/usr/local")) # 獲取父目錄 print(os.path.basename("/usr/local")) # 獲取最後一級,若是是文件顯示文件名,若是是目錄顯示目錄名 print(os.path.exists("/usr/local")) # 目錄/文件是否存在 print(os.path.isabs(".")) # 判斷是不是絕對路徑 print(os.path.isfile("/usr/local")) # 判斷是不是一個文件 print(os.path.isdir("/usr/local")) # 是不是一個路徑 print(os.path.join("/root",'hehe','a.sql')) # 拼接成一個路徑,系統能自動識別linux("/")和windows("\") print(os.path.getatime("len_os.py")) # 輸出最近訪問時間 print(os.path.getmtime("len_os.py")) # 輸出最近訪問時間 print(os.path.getctime("len_os.py")) # 輸出文件建立日期
os.access("../test.html", os.F_OK) #os.F_OK參數判斷path路徑是否存在此文件,返回布爾值
os.access("../test.html", os.R_OK) #os.R_OK參數判斷此文件是否可讀,返回布爾值
os.access("../test.html", os.W_OK) #os.W_OK參數判斷此文件是否可寫,返回布爾值
os.access("../test.html", os.X_OK) #os.X_OK參數判斷此文件是否可執行,返回布爾值
os.chown(path, uid, gid); #將指定的路徑的全部者和組ID更改成數字uid和gid。
os.chroot(path) #方法用於更改當前進程的根目錄爲指定的目錄,使用該函數須要管理員權限,path爲設置的根目錄路徑。
sys模塊 與python解釋器進行交互 import sys sys.argv # 命令行參數List,第一個元素是程序自己路徑 sys.exit(n) # 退出程序,正常退出時exit(0) sys.version # 獲取Python解釋程序的版本信息 sys.maxint # 最大的Int值 sys.path # 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform # 返回操做系統平臺名稱 sys.stdout.write('please:') # 向屏幕輸出一句話 val = sys.stdin.readline()[:-1] # 獲取輸入的值 time,datetime模塊 時間有三種表示方式,一種是時間戳、一種是格式化時間、一種是時間元組 import time,datetime print(time.timezone) # 本地時間和標準時間相差的時間,單位是s print(time.time()) # 返回當前時間戳
print(time.clock()) # 計算cpu處理執行的時間 print(time.sleep(1)) # 休眠,單位秒 print(time.gmtime()) # 把時間戳轉換成時間元組,若是不傳的話,默認取標準時區的時間戳 print(time.localtime()) # 把時間戳轉換成時間元組,若是不傳的話,默認取當前時區的時間戳 print(time.mktime(time.localtime())) # 把時間元組轉換成時間戳 print(time.strftime("%y%m%d %H%M%S")) # 將時間元組轉換成格式化輸出的字符串 print(time.strptime("20160204 191919","%Y%m%d %H%M%S")) # 將格式化的時間轉換成時間元組 print(time.struct_time) # 時間元組 print(time.asctime()) # 時間元轉換成格式化時間 print(time.ctime()) # 時間戳轉換成格式化時間 print(datetime.datetime.now()) # 固然時間格式化輸出 print(datetime.datetime.now()+datetime.timedelta(3)) # 3天后的時間 print(datetime.datetime.now()+datetime.timedelta(-3)) # 3天前的時間 time.asctime( time.localtime(time.time()) ) # 可讀格式獲取如今時間
import calendar
calendar.month(2021, 11) # 獲取2021年11月的日曆,先導入import calendar模塊 str類型的日期轉換爲時間戳 tss1 = '2018-10-10 23:40:00'#字符型時間格式 timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")#轉成時間數組,全部時間數組均可以.出方法來調用所須要的字段 timeStamp = int(time.mktime(timeArray))#轉成時間戳 修改str類型的日期格式 tss2 = "2013-10-10 23:40:00" timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S") otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) 時間戳轉換爲指定格式的日期 #time timeStamp = 1381419600 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) #datetime timeStamp = 1381419600 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S") 時間戳變成指定格式 #time now = int(time.time()) # 1533952277 timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray) #datetime now = datetime.datetime.now() otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
configparser模塊 一般用做配置文件的增刪改查
#生成conf文件
import configparser
conf = configparser.ConfigParser()
conf['mysql'] = {
'user': 'nihao',
'passwd': 123456,
'port': 3306
}
conf['redis'] = {}
conf['redis']['user'] = 'nihao'
conf['redis']['passwd'] = '123456'
conf['redis']['port'] = '6379'
with open('conf.txt', 'w') as configfile:
conf.write(configfile)
#讀取conf文件
import configparser
conf = configparser.ConfigParser()
conf.read('conf.txt') #讀取conf文件
sec = conf.sections() #獲取全部父節點值
opt = conf.options('mysql') #獲取指定父節點下的全部子節點key
item = conf.items('redis') #獲取指定父節點下的全部子節點的key,values
v_int = conf.getint('redis', 'passwd') #獲取指定節點的int數據
v_boolean = conf.getboolean('redis', 'tpye') #獲取指定節點的布爾值數據
v_float = conf.getfloat('redis', 'salary') #獲取指定節點的浮點數據
v_all = conf.get('redis', 'all') #獲取指定節點的全部類型數據
#修改conf文件
import configparser
conf = configparser.ConfigParser()
conf.read('conf.txt') #讀取conf文件
conf.add_section('db') #添加一個父類節點
conf.add_section('123')
conf.remove_section('123') #刪除一個父節點
conf.set('db','db_username','rainbol') #添加一個子節點並賦值
conf.set('db','db_password','123456')
conf.remove_option('mysql','user') #刪除一個子節點
conf.remove_option('mysql','passwd')
conf.set('mysql','username','root')
conf.set('mysql','password','654321')
conf.clear() #清空配置文件
conf.write(open('conf.txt','w',encoding='utf-8')) #修改完成寫入配置文件
itsdangerous模塊 #一種的加密方式,程序解析加密和加密字符串,能夠記錄TTL和鹽值
salt = 'saO)(&)H' #設置鹽值
t = itsdangerous.TimedJSONWebSignatureSerializer(salt,expires_in=600)#指定參數,第一個是鹽值,第二個是TTL加密過時時間
res = t.dumps({'username':'rainbol','password':'123456'})#設置加密的字典
print(res.decode())#取加密信息
session = 'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MjAwMTcwNCwiZXhwIjoxNTQyMDAyMzA0fQ.eyJ1c2VybmFtZSI6IkNoZW56dWFueWkxMjMiLCJwYXNzd29yZCI6IkN6eTEyMzQhISJ9.
tOdU5gNQdIVONPoD5DLxsW4lRcDX_n3Bg82RR5C48uXT5JhW7Z_UYqpZYd16p9tlT7moXM-T0Son07_KGaBJvA'
res = t.loads(session)#解析加密信息,若是加密信息不正確會報錯
print(res)
glod模塊 #過濾目錄
* ,?,[] #匹配規則 * :匹配0個或多個字符; ? :匹配單個字符; [] :匹配指定範圍內的字符
print(glob.glob('*.py'))#返回一個list,括號中填寫過濾條件,*.py表示取結尾爲py的文件
_list = glob.glob(BASEPATH+ os.sep + '*' + os.sep + '/*.html') #只獲取第二層路徑的html文件
_list = glob.glob('../*.html') #獲取上一層的html文件
platform模塊 #判斷操做系統,如os,linux,windows
import platform
import os
if platform.system().lower()== 'linux':
os.system('ls')
elif platform.system().lower()=='windows':
os.system('dir')
else:
pass
gevent模塊 #基於greenlet封裝,避免多線程切換致使io執行效率下降 import gevent from gevent import monkey monkey.patch_all() def run(name, url): r = requests.get(url) open(name + '.html', 'wb').write(r.content) url = {'rainbol01': 'https://www.cnblogs.com/RainBol/', 'rainbol02': 'https://www.cnblogs.com/RainBol/p/9505438.html', 'rainbol03': 'https://www.cnblogs.com/RainBol/p/10077388.html' } for name, url in url.items(): g = gevent.spawn(run, name, url) # 啓動 g.join() # 等待並切換
//阻塞等待分配任務完成後結束
l = []
for i in range(10):
g = gevent.spawn(run,name,url)
l = g.append(g)
g.joinall(l)
logger模板[1] #日誌是一種能夠追蹤某些軟件運行時所發生事件的方法。python封裝好了咱們可使用生成的日誌報告框架
import logging 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='test.log', filemode='w') # level 級別 = logging.DEBUG 設置debug級別
# format 格式徹底能夠自定義
# datefmt 根據format中的asctime來設置指定自定義時間
# filename 設置文件輸出格式,若是若是去掉filename和filemode將以屏幕輸出格式 # filemode 文件模式 # 'w'記錄到文件日誌中,在w模式下,至關於打開文件的寫操做,會覆蓋以前的記錄覆蓋 # 'a'記錄到文件日誌中,在a模式下,至關於打開文件的追加操做
# format固定變量格式 ''' %(name)s 打印日誌名稱 %(levelno)s 打印日誌級別的數值 %(levelname)s 打印對應filename參數中的設置的log路徑 %(pathname)s 打印當前執行程序的路徑 %(filename)s 打印文件名 %(module)s 打印日誌輸出函數的模塊名 %(lineno)d 記錄執行代碼行號 %(funcName)s 由哪一個function發出的log, 調用日誌輸出函數的函數名 %(created)f 當前時間,用UNIX標準的表示時間的浮點數表示; 日誌事件發生的時間--時間戳,就是當時調用time.time()函數返回的值 %(asctime)s 對應datefmt參數中設置的時間 %(msecs)d 日誌事件發生事件的毫秒部分 %(relativeCreated)d 日誌記錄建立時的時間(以毫秒爲單位),與加載日誌模塊的時間(一般在應用程序啓動時)相關 %(thread)d 打印線程id %(threadName)s 打印線程名稱 %(process)d 打印進程id %(message)s 打印日誌信息 ''' # 日誌級別 critical > error > warning > info > debug logging.debug('this is debug message') logging.info('this is info message') logging.warning('this is warning message') logging.error('this is error message') logging.critical('this is critical message')
logger模板[2] #既想輸出屏幕還輸出到文件用此格式 import logging #建立四個對象 logger = logging.getLogger()#拿到一個logger對象 filer = logging.FileHandler('test.log')#建立一個把test.log路徑放到FileHandler文件輸出對象 stream = logging.StreamHandler()#建立一個屏幕輸出對象 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#建立一個把format輸出到Formatter中的對象 filer.setFormatter(formatter)#fh文件添加輸出格式 stream.setFormatter(formatter)#ch屏幕添加輸出格式 #爲logger添加文件輸出格式和屏幕輸出格式 logger.addHandler(filer) logger.addHandler(stream) logger.setLevel(logging.DEBUG)#指定日誌級別設置爲DEBUG logger.debug('this is debug message') logger.info('this is info message') logger.warning('this is warning message') logger.error('this is error message') logger.critical('this is critical message')
logger擴展實例python
''' @File : rainbolog.py @Copyright : Rainbol @Date : 2019/9/25 @Desc : ''' import logging from logging import handlers from conf.setting import logs_level class SingletonLog(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = object.__new__(cls) return cls._instance class RainLog(SingletonLog): def __new__(cls, *args, **kwargs): return super().__new__(cls) def __init__(self, log_where, logs_level='debug', backCount=5, when='D', interval=1): '''log_where日誌絕對路徑,logs_level日誌等級''' self.level = logs_level self.logger = logging.getLogger('rainlog') # 拿到一個logger對象 self.stream = logging.StreamHandler() # 建立一個屏幕輸出對象 fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') # 定義日誌格式 self.bl = handlers.TimedRotatingFileHandler(filename=log_where, when=when, interval=interval, backupCount=backCount, encoding='utf-8') self.bl.setFormatter(fmt) # fh文件添加輸出格式 self.stream.setFormatter(fmt) # ch屏幕添加輸出格式 # 爲logger添加文件輸出格式和屏幕輸出格式 self.logger.addHandler(self.stream) self.logger.addHandler(self.bl) self.logger.setLevel(getattr(logging, self.level.upper())) # 指定日誌級別設置爲DEBUG def write(self, connect): '''寫日誌,connect:寫入信息''' if self.level.lower() == logs_level.lower(): res = getattr(self.logger, self.level.lower(), 'debug') res(connect) # 添加下面一句,在記錄日誌以後移除句柄 self.logger.removeHandler(self.stream) self.logger.removeHandler(self.bl) else: pass if __name__ == '__main__': # logger = RainLog('your_path') # logger.write('your_message') pass
hashlib模塊
import hashlib password1 = '123456' res = password1.encode()#將密碼轉出二進制,password2 = b'123456'或者直接加b m = hashlib.md5(res)#進行md5加密 print(m.hexdigest())#顯示md5加密 加鹽:二級加密,保證數據的安全,咱們會在md5加密代碼前加上一個特定的字符串,如123456helloworld,輸入密碼爲123456,進過加鹽對123456helloworld進行md5加密,當用戶登陸輸入密碼,代碼自動在用戶輸入密碼後加鹽,轉出md5與數據庫匹配 除了MD5還有sha.224,sha256更安全,因爲md5算法是不可逆的,因此按照實際業務來實現算法 雙重加密 加密兩次,咱們使用os.urandom(n) #表示一個生成n個字節隨機字符串,固然每次打印生成的結果確定是不同的 uuid加密 import uuid res=uuid.uuid4() #根據機器號時間等信息生成的隨機序列號 #e6684777-5166-455f-8c48-c6f5f3e79d2c import os from hashlib import md5 req = os.urandom(24) res = md5(os.urandom(24)).hexdigest() print(res) #002747ea4bb0852767c9449307f8da93
importlib模塊
#實現動態導入模塊並執行
import importlib mode = 'libtest.importlib_test' #mode爲libtest文件下的importlib_test.py文件 fuc = 'run' #文件中的run函數名稱 moc = importlib.import_module(mode) #將mode變量導入,該模塊會拿到py文件對象 res = getattr(moc,fuc) #再經過getattr傳入對象和函數名稱 res()#最後執行模塊方法
heapq模塊
#從一個集合中查找最大最小的N個元素——Python heapq 堆數據結構 import heapq num = [23,213,1,23,2,23,24,5,345,34.324,5,3,52] max= heapq.nlargest(3,num)#顯示列表中的最大前三個 min = heapq.nsmallest(3,num)#顯示列表中的最小前三個# heapq.nlargest(n, iterable[, key])第三參數key的使用 portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] print(heapq.nlargest(3,portfolio,lambda x:x['shares']))#從例子中能夠看出x['shares']能夠取關鍵字shares值的數據做爲排列規則,而且再取整行數據 #>>[{'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'ACME', 'shares': 75, 'price': 115.65}]
callable() #判斷是否爲函數
def hanshu(): pass print(callable(hanshu))#true print(callable('我不是函數'))#false
min()函數 判斷最小 print(min('abc123')) print(min([2,3,4,5,6,7,1])) print(min({1:'213',2:'42'})) print(min((2,3,4,5,6,7,8,1))) print(min((({4:'a',2:'b',1:'c'}))))#無論裏面有多少層 print(min({'a':'213','b':'42'})) #key參數 print(min({"username":"123","password":"321"},{"username":"342","password":"5343"},key=lambda x:x["username"]))#多字典函數時指定函數區分 #default參數 print(min('', default='默認值'))#空字符串,空列表,空元祖,空字段,可設返回默認值
下面爲第三方庫mysql
faker模塊 不是打LoL的faker
# pip install faker #github地址 https://github.com/joke2k/faker #中文官方文檔 https://faker.readthedocs.io/en/master/locales/zh_CN.html# import faker #該模塊主要是用來作測試的假數據或者僞造數據 f2 = faker.Faker(locale='zh-CN')#指定中文,若是不填就是英文數據,也能夠指定其餘國外地區 #經常使用 print(f2.ssn())#身份證號 print(f2.phone_number())#手機號 print(f2.email())#郵箱 print(f2.address())#地址 print(f2.name())#姓名 print(f2.postcode()) print(f2.street_address())#街道地址 print(f2.street_name())#街道名 print(f2.street_suffix())#街、路 print(f2.street_address())#街道地址 print(f2.date())#隨機日期 print(f2.ipv4())#隨機IP4地址 print(f2.url())#隨機URL地址 print(f2.phone_number())#隨機生成手機號 print(f2.simple_profile())#隨機檔案信息
#hypothesis模塊 高級測試庫,造一些日常測試中難以發現的測試數據 #使用:pip install hypothesis import unittest from hypothesis import given, settings import hypothesis.strategies as st def add(a, b): """實現加法運算""" return a + b class AddTest(unittest.TestCase): @settings(max_examples=100) # 控制隨機數的生成次數, @given(a=st.integers(), b=st.integers()) # 裝飾測試用例,調用strategies 模塊下面的 integers() 方法生成隨機的測試數 def test_case(self, a, b): print("a->", a) print("b->", b) c1 = a + b # 實際結果數據 c2 = add(a, b) # 測試add函數的結果數據 self.assertEqual(c1, c2) @settings(max_examples=5) @given(c=st.text(), d=st.dates(), e=st.data(), f=st.binary()) def test_case2(self, c, d, e, f): print('c--->', c) print('d--->', d) print('e--->', e) print('f--->', f) @settings(max_examples=5) @given(g=st.booleans(), j=st.characters(), l=st.datetimes(), m=st.times()) def test_case2(self, g, j, l,m): print('g--->', g) print('j--->', j) print('l--->', l) print('m--->', m) if __name__ == '__main__': unittest.main()
jsonpath模塊 #方便取json的模塊
# 安裝 pip install jsonpath import jsonpath es = { "mappings": { "article": { "properties": { "type": "string", "analyzer": "english" } , "post_date": { "type": "date" }, "title": { "type": "string" }, "publiser_id": { "type": "long" } } } } result01 = jsonpath.jsonpath(es, 'mappings') # 參數1:傳一個正確的json,參數2:傳想要獲取的key,返回一個傳入的鍵的value並以列表形式返回 result02 = jsonpath.jsonpath(es, 'article') # 返回False,若是超過第一層就要使用$..來查找,以下↓ result03 = jsonpath.jsonpath(es, '$..analyzer') # 返回['english'] print(result03)
在linux常見使用curl,該模塊能夠在window使用相似於curl的功能
pip install httpie 以後在終端輸入http看看有沒有安裝成功 http -v www.baidu.com #請求返回詳細信息 http www.baidu.com > a.txt #重定向到一個文件 http -h #只顯示header http -b #只顯示body http -d #下載保存頁面 和重定向同樣 http -a your_username:your_password #--auth-type=digest http 網站 User-Agent:用戶代理 'Cookie:cookie' Referer:來源 #用來修改請求頭 http --proxy=http:http://192.168.1.254:8080 xxx.com #使用代理來請求 其餘 https://www.jianshu.com/p/65b1d65873f5
# pip install emoji python操做emoji from emoji import emojize print(emojize(":thumbs_up:"))#默認::中間爲分割符,裏面是存儲表情名 print(emojize("Python is fun :thumbs_up:")) print(emojize("Python is fun @!thumbs_up!@", delimiters=("@!", "!@")))#能夠修改默認分隔符,自定義分割符 print(emojize("hello:Christmas_tree::Christmas_tree:world!")) from emoji import emoji_lis emj = emojize("Python is fun :thumbs_up:") print(emoji_lis(emj)) #尋找emoji返回列表形式 [{'location': 17, 'emoji': '👍'}] #👍 #Python is fun 👍 #Python is fun 👍 #hello🎄🎄world! #[{'location': 14, 'emoji': '👍'}]
版權聲明:本文原創發表於 博客園,做者爲 RainBol 本文歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然視爲侵權。linux