在用戶註冊、登錄頁面爲了防止暴力請求,能夠加入驗證碼。若是驗證碼錯誤,則不須要繼續處理,能夠減輕服務器的壓力html
使用驗證碼也是一種有效防止csrf的方法前端
def verifycode(request): #引入繪圖模塊 from PIL import Image, ImageDraw, ImageFont #引入隨機函數模塊 import random #定義變量,用於畫面的背景色、寬、高 bgcolor = (random.randrange(20, 100), random.randrange( 20, 100), random.randrange(20, 100)) width = 100 height = 50 #建立畫面對象 im = Image.new('RGB', (width, height), bgcolor) #建立畫筆對象 draw = ImageDraw.Draw(im) #調用畫筆的point()函數繪製噪點 for i in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, height)) fill = (random.randrange(0, 255), 255, random.randrange(0, 255)) draw.point(xy, fill=fill) #定義驗證碼的備選值 str = '1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm' #隨機選取4個值做爲驗證碼 rand_str = '' for i in range(0, 4): rand_str += str[random.randrange(0, len(str))] #構造字體對象 font = ImageFont.truetype(r'C:\Windows\Fonts\AdobeArabic-Bold.otf', 40) #構造字體顏色 fontcolor1 = (255, random.randrange(0, 255), random.randrange(0, 255)) fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255)) fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255)) fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255)) #繪製4個字 draw.text((5, 2), rand_str[0], font=font, fill=fontcolor1) draw.text((25, 2), rand_str[1], font=font, fill=fontcolor2) draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3) draw.text((75, 2), rand_str[3], font=font, fill=fontcolor4) #釋放畫筆 del draw #內存文件操做 import io buf = io.BytesIO() #將圖片保存在內存中,文件類型爲png im.save(buf, 'png') #將內存中的圖片數據返回給客戶端,MIME類型爲圖片png response = HttpResponse(buf.getvalue(), 'image/png') #將驗證碼的值寫入cookie,以被前端瀏覽器驗證驗證碼 # response.set_cookie("verifycode", rand_str) # 存入session,用於作進一步驗證 request.session['verifycode'] = rand_str return response
def login(request): if request.method == "GET": infoStr = "<h1>sunck is a good man</h1>" # infoStr = "<script>alert('sunck good')</script>" return render(request, "login.html", {"infoStr":infoStr}) else: #判斷驗證碼 verifycode = request.POST.get("verifycode") if not verifycode.upper() == request.session.get("verifycode").upper(): return redirect("/login/") username = request.POST.get("username") password = request.POST.get("password") if username == "sunck" and password == "sunck1999": return redirect("/index/") else: return redirect("/login/")
一個輕量級、底層的插件系統,能夠介入Django的請求和響應過程,處理Django的輸入或輸出python
每一箇中間件組件都是一個獨立的Python類django
在App目錄下建立名爲middlewares的包segmentfault
在包中建立本身的中間件類文件瀏覽器
verifycodeMiddleware.py服務器
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect class VerifycodeMiddleware(MiddlewareMixin): def process_request(self, request): print("***************", request.path) if request.path == "/login/" and request.method == "POST": # 判斷驗證碼 verifycode = request.POST.get("verifycode") if not verifycode.upper() == request.session.get("verifycode").upper(): return redirect("/login/")
在settings.py文件中配阿置MIDDLEWAREcookie
'myApp.middlewares.verifycodeMiddleware.VerifycodeMiddleware'
6-django——admin站點管理session