1.django用post傳檔案,如何接收和下載?
data= https://www.cnblogs.com/shengjunqiye/p/request.FILES.get('file')#接收到的資料型別是<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> # print(data,type(data)) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> with open(r'C:\Users\33101\Desktop\12\新建1111.txt','wb') as p:#這樣可以寫進檔案,不能直接p.write(chunks()) for chunk in data.chunks(): p.write(chunk) #讀取發送過來的檔案,并用base64加密 a=request.FILES.get("file").read() print("傳過來的檔案:",a) b=base64.b64encode(a) print('加密后的檔案:',b) #接收多個檔案: files=request.FILES.getlist('up_file') print(files,type(files)) for i in files: print(i.read())#讀檔案,得到二進制 # print('*******************') print(i.name)#獲取檔案名字 i.size#獲取檔案大小的數字(單位是B)
2.阿里云oss上傳/洗掉圖片
#阿里云oss上傳圖片 import oss2,datetime data = request.FILES.get('file') # 獲取post傳過來的檔案,得到<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(data.file) #這個就是你傳過來的檔案內容 #一下四項都是在阿里云獲取的 OSS_URL = '' OSS_NAME = '' ALI_KEY_ID ='' ALI_KEY = '' OSS_URL_HTTPS = 'https://'+OSS_NAME+'.'+OSS_URL+'.com' #拼接個路徑,是存放在oss服務器上的位置,注意要帶上檔案名字 #特別注意:在windows環境拼接的路徑和linux上的路徑不同,要注意區別, oss_path = os.path.join('ele_seal', 'test', datetime.datetime.now().strftime('%Y%m%d'),'wwdf.png')#如果在windows機器上就會拼接成windows識別的路徑,放到服務器上就不好使了 # oss_path = 'ele_seal/test/20200904/110.png'#手動拼接一個適合linux服務器上的路徑 # 上傳檔案 # auth = oss2.Auth(ALI_KEY_ID, ALI_KEY) # bucket = oss2.Bucket(auth, OSS_URL, OSS_NAME) # result = bucket.put_object(oss_path,data.file)#oss_path就是你檔案存放在oss服務器的位置(包含檔案名),data.file就是你post傳過來的檔案的內容(.file是固定用法) # print(result.status)#如果回傳200就證明上傳成功 #訪問上傳的圖片(固定寫法) OSS_URL_HTTPS +'/'+ oss_path #洗掉已上傳的檔案 auth = oss2.Auth(ALI_KEY_ID, ALI_KEY) bucket = oss2.Bucket(auth, OSS_URL, OSS_NAME) result = bucket.delete_object('ele_seal/test/20200904/110.png') print(result.status)#回傳引數204就洗掉成功,如果一直卡著,那就證明找不到該檔案
3.正匹配手機號碼:
# 判斷手機號碼格式是否正確 regular = '^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(166)|(17[2|8])|(18[0,5-9])|(19[8|9]))\d{8}$' regular_obj = re.compile(regular) check_phone = re.match(regular_obj, phone)
4.獲取http請求頭內容
用request.META獲取的是個大字典,就是請求頭所有內容,剩下的就用get取值 a=request.META.get("CONTENT_TYPE") #如果是固定的請求頭就直接變成大寫,所有的-都變成——就可以獲取值了 b=request.META.get("HTTP_APPID")#如果是手動加的就必須以HTTP_開頭,再加你寫的鍵(全部大寫,遇到-就變成_)即可 c=request.META.get("HTTP_TIME") d=request.META.get("HTTP_SIGN")

5.AES加密
from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex import time #token加密資訊 CRYPTO_KEY = 'A@G#X*NHA@G#X*No'#必須16位,這里是字串 CRYPTO_OFFSET = b'qqqqqqqqqqqqqqpq'#必須16位,這里是二進制 class HeaderCrypto(object): ''' token 資訊的加密與解密 ''' def __init__(self, crypto_key, crypto_offset): ''' :param crypto_key=加密需要的key :param crypto_offset=加密需要的偏移量 crypto_model=crypto采用的加密模式 ''' self.crypto_key = crypto_key.encode('utf-8') self.crypto_offset = crypto_offset self.crypto_model = AES.MODE_CBC def add_to_16(self, cry_con): ''' :param cry_con=需要加密的json字串進行16位倍數處理 :return: 16位倍數的字串 不足16位倍數的用0進行填充 ''' zero_num = 16 - (len(cry_con.encode('utf-8')) % 16) if len(cry_con.encode('utf-8')) % 16 else 0 res_cry_con = cry_con + ('\0' * zero_num) return res_cry_con.encode('utf-8') def encrypt(self, cry_con): ''' :param cry_con=需要加密的字串資訊 :return: 加密后的字串資訊 因為AES加密后的字串不一定是ascii字符集的,輸出保存可能存在問題,所以這里轉為16進制字串 ''' res_cry_con = self.add_to_16(cry_con) cryptos = AES.new(self.crypto_key, self.crypto_model, self.crypto_offset) cipher_text = cryptos.encrypt(res_cry_con) return b2a_hex(cipher_text) def decrypt(self, cry_con): ''' :param cry_con=需要解密的字串資訊 :return: 解密后的json字串 解密后,去掉補足的空格用strip() 去掉 ''' cryptos = AES.new(self.crypto_key, self.crypto_model, self.crypto_offset) plain_text = cryptos.decrypt(a2b_hex(cry_con)) return bytes.decode(plain_text).rstrip('\0') crypto_dict = { 'req_server': 'self.req_server', 'source_sign': 'self.source_sign', 'unique_sign': 'self.unique_sign', 'phonenum': 'phonenum', 'user_id': 'user_id', 'user_type': 0, 'datetime': int(time.time()), } obj=HeaderCrypto(CRYPTO_KEY,CRYPTO_OFFSET) a=obj.encrypt(str(crypto_dict)) print(a)#加密后的值 # c=b'722501109bdd032f0ff9b4090dce0ce028803780ce695910b927ef646c8e3329c07a6b6d589a3ad72c1bca451360fd8cb3cd9d84682bd85d9066d1fd56cca66a8a63a60c2e483a7ccac5018401683d220459dfd1bd9ad4a60a6ead38ff637f7765143aa7d732c0372a5cdb3e460726f00e51961d650a19b57bf1f495d0b13a5c0353746f10cca0531bd5ce73dba790a475c572c363eeaaede6d0564f69de1ef0a2ac858013ed4bd281084496a9b11401bb8a95700782a0139eb4de6d680eb3ed' # # d=obj.decrypt(c)#解密時傳的引數是二進制還是字串均可, # print(d,type(d))#解密后的值,是字串 # {'req_server': 'self.req_server', 'source_sign': 'self.source_sign', 'unique_sign': 'self.unique_sign', 'phonenum': 'phonenum', 'user_id': 'user_id', 'user_type': 0, 'datetime': 1599530672}
6.字串與二進制互轉
# 字串轉二進制 a='我是誰' # 法一 # b=a.encode() # print(b,type(b)) # b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81' <class 'bytes'> # 法二 # c=bytes(a,'utf-8')#utf-8不可省略 # print(c,type(c)) # b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81' <class 'bytes'> # 二進制轉字串 e=b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81' # 法一 c=e.decode() print(c,type(c)) # 我是誰 <class 'str'> # 法二 f=str(e,'utf-8')#正確的寫法,結果是 我是誰 <class 'str'> # f=str(e) #錯誤的寫法,結果是 b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81' <class 'str'> print(f,type(f))
7.字串轉字典(eval和ast.literal_eval)
a='{"r":113}' print(a,type(a)) b=eval(a)#用eval很危險 print(b,type(b)) # {"r": 113} <class 'dict'> # eval()函式功能強大,但也很危險,若程式中有以下陳述句: s=input(‘please input:’) print (eval(s)) # 下面舉幾個被惡意用戶使用的例子: # 1、運行程式,如果用戶惡意輸入: # eval(“import(‘os’).system(‘ls -l’)”) # 2、運行程式,如果用戶惡意輸入: # eval(“open(‘a.txt’).read()”) # 如果,當前目錄中恰好有一個檔案,名為a.txt,則惡意用戶變讀取到了檔案中的內容, # 3、運行程式,如果用戶惡意輸入 # 如果,當前目錄中恰好有一個檔案,名為a.txt,則惡意用戶洗掉了該檔案,/q :指定靜音狀態,不提示您確認洗掉 # eval(“import(‘os’).system(‘rm -rf a.txt’)”) # 解決方法 import ast c=ast.literal_eval(a) print(c,type(c)) # {"r": 113} <class 'dict'>
8.讀圖片給圖片進行base64加密
import base64 with open(r'C:\Users\33101\Desktop\234.jpg','rb') as f: m = base64.b64encode(f.read()) print(m)#加密后的結果
9.requests接收檔案
import requests req = requests.get("http://www.baidu.com/") //發起GET請求 print(req.text) //列印回應內容 req.ok // 檢查回傳碼是不是 '200 OK',如果是則回傳True,否則回傳False req.url // 查看請求的URL,也就是'http://www.baidu.com/' req.text // 查看回傳的回應內容,回傳的是Unicode資料,一般用于回傳文本資料 req.content // 查看回傳的回應內容,回傳的是二進制資料,一般用于回傳圖片,檔案等二進制資料 req.status_code // 查看回傳的HTTP狀態碼,如 200,404,502 等 req.reason // 查看回傳的HTTP狀態碼文本原因,如 'Not Found', 'OK' 等 req.cookies // 查看回傳的cookies資訊 req.header // 查看回傳的頭部資訊 #帶引數的get請求: import requests params = { "wd": "hello", "rsv_spt": 1 } req = requests.get("http://www.baidu.com/", params=params) //相當于 requests.get("http://www.baidu.com/s?wd=hello&rsv_spt=1") print(req.text) #偽造請求頭資訊,發起GET請求: import requests headers = { //定義請求頭資訊,通常只定義 User-Agent,其他請求頭資訊可以通過 F12 界面查看,參考:https://www.cnblogs.com/pzk7788/p/10500101.html "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" } req = requests.get("http://www.baidu.com/", headers=headers) print(req.text)
10.二進制生成圖片BytesIO
from PIL import Image from io import BytesIO i = Image.open(BytesIO(二進制內容))#二進制可以是讀的圖片或者是requests獲取的網路圖片 i.save(r'C:\Users\33101\Desktop\12\1222223.png') #例: from PIL import Image from io import BytesIO r=requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599671244609&di=101c0cc3ab7c6ceb6a7e39433a1f2e94&imgtype=0&src=https://www.cnblogs.com/shengjunqiye/p/http%3A%2F%2Fa2.att.hudong.com%2F36%2F48%2F19300001357258133412489354717.jpg') i = Image.open(BytesIO(r.content)) i.save(r'C:\Users\33101\Desktop\12\2230000.png')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/1963.html
標籤:Python
