以下是详细讲解“Django中使用pillow实现登录验证码功能(带刷新验证码功能)”的完整攻略,包含两条示例说明:
在Django中使用pillow来生成验证码实现登录验证功能,首先需要安装pillow库。可以通过以下命令在终端中安装:
pip install pillow
在app.views.py文件中添加生成验证码的函数generate_captcha()。
from PIL import Image, ImageDraw, ImageFont
import random, string
def generate_captcha():
# 随机生成字符串
captcha_text = ''.join(random.sample(string.ascii_letters + string.digits, 4))
# 设置图片尺寸
img_size = (100, 30)
# 设置字体
font = ImageFont.truetype("arial.ttf", 28)
# 设置背景颜色
bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 设置字体颜色
font_color = (255, 255, 255)
# 创建画布
img = Image.new(mode="RGB", size=img_size, color=bg_color)
draw = ImageDraw.Draw(img)
# 将验证码字符串写到画布上
draw.text((10, 0), captcha_text, font=font, fill=font_color)
# 噪点干扰
for i in range(random.randint(120,130)):
draw.point([random.randint(0,img_size[0]),random.randint(0,img_size[1])],fill=(0,0,0))
# 画框
draw.rectangle([1,1,img_size[0]-1,img_size[1]-1],outline=(255,255,255))
# 将生成的验证码图片保存
img.save('app/captcha.png', 'PNG')
# 返回验证码字符串
return captcha_text
在app.urls.py文件中,修改路径为/captcha/,视图调用函数为generate_captcha()。
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('captcha/', views.generate_captcha, name='captcha'),
]
在login.html文件中,添加img标签和a标签用于刷新验证码。
<!DOCTYPE html>
<html>
<head>
<title>login</title>
</head>
<body>
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<img src="{% url 'captcha' %}" id="captcha"><br>
<a href="javascript:void(0)" onclick="document.getElementById('captcha').src='{% url 'captcha' %}?'+Math.random()">刷新</a>
<br>
<label for="captcha_input">Captcha:</label><br>
<input type="text" id="captcha_input" name="captcha_input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
在views.py文件中添加login()函数用于验证用户输入的用户名、密码和验证码是否正确。
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
captcha_input = request.POST['captcha_input']
captcha_text = request.session.get('captcha_text')
user = authenticate(request, username=username, password=password)
if user is not None and captcha_input.lower() == captcha_text.lower():
login(request, user)
return redirect('index')
else:
return redirect('login')
else:
captcha_text = generate_captcha()
request.session['captcha_text'] = captcha_text
return render(request, 'login.html', {'captcha_text': captcha_text})
假设我们有一个名为myapp的app,我们需要修改myapp中的views.py文件来生成验证码。
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .models import Post
from .forms import PostForm
from PIL import Image, ImageDraw, ImageFont
import random, string
def generate_captcha():
# 随机生成字符串
captcha_text = ''.join(random.sample(string.ascii_letters + string.digits, 4))
# 设置图片尺寸
img_size = (100, 30)
# 设置字体
font = ImageFont.truetype("arial.ttf", 28)
# 设置背景颜色
bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 设置字体颜色
font_color = (255, 255, 255)
# 创建画布
img = Image.new(mode="RGB", size=img_size, color=bg_color)
draw = ImageDraw.Draw(img)
# 将验证码字符串写到画布上
draw.text((10, 0), captcha_text, font=font, fill=font_color)
# 噪点干扰
for i in range(random.randint(120,130)):
draw.point([random.randint(0,img_size[0]),random.randint(0,img_size[1])],fill=(0,0,0))
# 画框
draw.rectangle([1,1,img_size[0]-1,img_size[1]-1],outline=(255,255,255))
# 将生成的验证码图片保存
img.save('myapp/captcha.png', 'PNG')
# 返回验证码字符串
return captcha_text
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
captcha_input = request.POST['captcha_input']
captcha_text = request.session.get('captcha_text')
user = authenticate(request, username=username, password=password)
if user is not None and captcha_input.lower() == captcha_text.lower():
login(request, user)
return redirect('index')
else:
return redirect('login')
else:
captcha_text = generate_captcha()
request.session['captcha_text'] = captcha_text
return render(request, 'login.html', {'captcha_text': captcha_text})
假设我们需要更改验证码图片的尺寸,可以修改generate_captcha()函数中的img_size变量。
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .models import Post
from .forms import PostForm
from PIL import Image, ImageDraw, ImageFont
import random, string
def generate_captcha():
# 随机生成字符串
captcha_text = ''.join(random.sample(string.ascii_letters + string.digits, 4))
# 设置图片尺寸 (200, 60)
img_size = (200, 60)
# 设置字体
font = ImageFont.truetype("arial.ttf", 36)
# 设置背景颜色
bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# 设置字体颜色
font_color = (255, 255, 255)
# 创建画布
img = Image.new(mode="RGB", size=img_size, color=bg_color)
draw = ImageDraw.Draw(img)
# 将验证码字符串写到画布上
draw.text((10, 0), captcha_text, font=font, fill=font_color)
# 噪点干扰
for i in range(random.randint(200, 210)):
draw.point([random.randint(0,img_size[0]),random.randint(0,img_size[1])],fill=(0,0,0))
# 画框
draw.rectangle([1,1,img_size[0]-1,img_size[1]-1],outline=(255,255,255))
# 将生成的验证码图片保存
img.save('myapp/captcha.png', 'PNG')
# 返回验证码字符串
return captcha_text
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
captcha_input = request.POST['captcha_input']
captcha_text = request.session.get('captcha_text')
user = authenticate(request, username=username, password=password)
if user is not None and captcha_input.lower() == captcha_text.lower():
login(request, user)
return redirect('index')
else:
return redirect('login')
else:
captcha_text = generate_captcha()
request.session['captcha_text'] = captcha_text
return render(request, 'login.html', {'captcha_text': captcha_text})
这样我们就完成了Django中使用pillow实现登录验证码功能(带刷新验证码功能)的完整攻略。
本文链接:http://task.lmcjl.com/news/14334.html