python_django__验证码
Posted Vera_y
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_django__验证码相关的知识,希望对你有一定的参考价值。
验证码:在用户注册/登陆时使用,为了防止暴力请求,减轻服务器压力,也是防止csrf的一种方式。
运行环境:python django
对应template模块htm函数:
登陆页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>验证码</title> </head> <body> <form method="post" action="{% url ‘inn:verificationcheck‘%}"> <!--反向解析--> <!--<form method="post" action="/sunck/verificationcheck/"> --> {% csrf_token %} <input type="text" name="verification_code"/> <img src="/sunck/verification_code/"> <input type="submit" value="登陆"/> <span>{{ flag }}</span> <!--状态码--> </form> </body> </html>
登陆成功页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆成功</title> </head> <body> <h1>登陆成功</h1> </body> </html>
对应url.py配置:
项目级:
from django.contrib import admin from django.urls import include from django.conf.urls import url from my_inn import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘sunck/‘,include(‘my_inn.urls‘,namespace=‘inn‘)), # 方便不同的app的管理 # namespace :与url的反向解析有关 ]
应用级:
from django.conf.urls import url from django.urls import path from . import views app_name=‘inn‘ urlpatterns = [ url(r‘^verification_code/$‘, views.verification_code), url(r‘verificationfile/$‘,views.verificationfile), url(r‘verificationcheck/$‘, views.verificationcheck,name=‘verificationcheck‘), ]
对应views.py文件函数:
from django.shortcuts import render,redirect from PIL import Image, ImageDraw, ImageFont # 引入绘图模块 import random # 引入随机函数模块 from django.http import HttpResponse from io import BytesIO # 在内存中创建 # 颜色的填充 def get_random_color(): color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) return color def verification_code(request): # 1.1 定义变量,宽,高,背景颜色 width = 130 height = 50 background_color = get_random_color() # 1.2 创建画布对象 image = Image.new(‘RGB‘, (width, height), background_color) # 1.3 创建画笔对象 draw = ImageDraw.Draw(image) # 1.4 调用画笔的point()函数绘制噪点 for i in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, height)) # 在尺寸内画点 draw.point(xy, fill=get_random_color()) # 1.5 调用画笔的line()函数制造线 for i in range(0, 5): xy_start = (random.randrange(0, width), random.randrange(0, height)) xy_end = (random.randrange(0, width), random.randrange(0, height)) draw.line((xy_start, xy_end), fill=get_random_color()) # 2 用draw.text书写文字 rand_python = ‘‘ # 随机选取4个值作为验证码 for i in range(4): random_number = str(random.randint(0, 9)) # 数字0-9 random_lower_letter = chr(random.randint(97, 122)) # 字母a-z random_upper_letter = chr(random.randint(65, 90)) # 字母A-Z rand_python += random.choice([random_number, random_lower_letter, random_upper_letter,]) color = get_random_color() # 构造字体颜色 text_color = [0, 0, 0] # for j in range(2): if color[j]-background_color[j] <= 30: text_color[j] = 255-color[j] else: text_color[j] = color[j] # 验证码字体及颜色 draw.text((i * (width/4) + 10, 2), rand_python[i], tuple(text_color), font=ImageFont.truetype(r‘C:WindowsFontsCHILLER.TTF‘, 40), align=‘center‘) # 3 释放画笔 del draw # 存入session,用于做进一步的验证 request.session[‘verification_code‘] = rand_python # 内存文件操作 buf = BytesIO() # 将图片保存在内存中,文件类型为png image.save(buf, ‘png‘) # 将内存中的图片数据返回给客户端,MIME类型为图片png return HttpResponse(buf.getvalue(), ‘image/png‘) def verificationfile(request): rflag = request.session.get("flag",True) str = "" if rflag ==False: str = "请重新输入" request.session.clear() return render(request,‘myMain/verificationfile.html‘,{"flag":str}) def verificationcheck(request): # 把接收到的验证码拿进来对比session中存储的验证码 code1 = request.POST.get("verification_code").upper() # 不区分大小写 code2 = request.session[‘verification_code‘].upper() if code1 == code2: # 成功跳转页面 return render(request,‘myMain/success.html‘) else: # 不成功重定向 request.session["flag"] = False return redirect(‘/sunck/verificationfile/‘)
view.py代码转自:https://blog.csdn.net/weixin_43830248/article/details/86670064
以上是关于python_django__验证码的主要内容,如果未能解决你的问题,请参考以下文章