''' pillow:是python處理圖片的模塊,很強大 '''
import random
from PIL import Image, ImageDraw, ImageFont
def picture_code():
def get_char():
'''通過數字獲取ASCII表中的對應字母'''
return chr(random.randint(65, 90))
def get_color():
'''獲取隨機顏色'''
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# mode:色系 size:寬高 color:顏色
# RGB顏色對照表:https://tool.oschina.net/commons?type=3
img = Image.new(mode='RGB', size=(120, 50), color=(220, 220, 220))
# 創建畫筆對象
draw = ImageDraw.Draw(img, mode='RGB')
# 畫點 xy:基於圖片的坐標,fill:顏色
for i in range(10):
draw.point([random.randint(0, 120), random.randint(0, 50)], fill='green')
# 畫線 xy:(起點坐標,終點坐標),width:粗細
for i in range(5):
draw.line(
[random.randint(0, 120), random.randint(0, 50), random.randint(0, 120), random.randint(0, 50)],
fill='red'
)
# 畫圓或弧線 start and end:角度
for i in range(3):
x = random.randint(0, 120)
y = random.randint(0, 50)
x2 = x + 4
y2 = y + 4
draw.arc([x, y, x2, y2], start=0, end=90, fill='red')
# 注意點:.ttf文件路徑不能含有中文
font = ImageFont.truetype('fonts/domi.ttf', 35)
char_list = []
for i in range(5):
char = get_char()
char_list.append(char)
height = random.randint(10, 15)
draw.text([18 * (i + 1), height], text=char, fill='red', font=font)
char_code = ''.join(char_list)
return img, char_code
if __name__ == '__main__':
img, r = picture_code()
# 創建在內存中,這裡直接生成在本地,方便自己調式查看
with open('code.png', 'wb') as f:
img.save(f, format='png') # format:格式
print(r)
首先後端需要先定義一個生成驗證碼的路由和視圖。
path('img_code/', account.img_code, name='img_code'),
def img_code(request):
img, char_code = picture_code()
# 將圖片數據寫到內存
stream = BytesIO()
img.save(stream, format='png')
# 將驗證碼放到session中 也可以放到redis中
request.session['image_code'] = char_code
# 圖片驗證碼有效期,單位秒
request.session.set_expiry(settings.IMAGE_CODE_EXPIRY)
return HttpResponse(stream.getvalue())
怎麼在前端頁面中展示驗證碼:
<img id="img_code" height="34" width="120" src="{% url "img_code" %}" alt="">
完整頁面代碼:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="account">
<h2 class="text-center">用戶登錄</h2>
<form id="form_data">
{
% csrf_token %}
{
% for field in form %}
{
% if field.label == '驗證碼' %}
<div class="form-group">
<label for="{
{ field.id_for_label }}">{
{
field.label }}</label>
<div class="row">
<div class="col-xs-6">
{
{
field }}
<span class="error_msg"></span>
</div>
<div class="col-xs-6">
<img id="img_code" height="34" width="120" src="{% url "img_code" %}" alt="">
</div>
</div>
</div>
{
% else %}
<div class="form-group">
<label for="{
{ field.id_for_label }}">{
{
field.label }}</label>
{
{
field }}
<span class="error_msg"></span>
</div>
{
% endif %}
{
% endfor %}
<div>
<button type="button" id="login" class="btn btn-primary">登 錄</button>
<div class="pull-right">
<a href="{% url 'login_sms' %}">短信驗證碼登錄>>></a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
發送登錄數據和點擊刷新驗證碼:
// 發送登錄數據
function sendLoginData() {
// 獲取用戶輸入的所有數據
// 將數據發送到後端
// 根據響應結果進行一些頁面效果處理
// 綁定點擊事件
$('#login').click(function () {
var data = $('#form_data').serialize(); //拿到form表單中的所有數據
$.ajax({
url: '{% url 'login' %}',
type: 'post',
data: data,
success:function (res) {
if (res.status){
location.href = res.path;
}else{
$.each(res.error_msg,function (k,v){
$('#id_' + k).next().text(v)
})
}
}
})
})
}
// 點擊刷新圖片驗證碼的事件
function refreshImageCode() {
$('#img_code').click(function () {
var oldSrc = $(this).attr('src');
$(this).attr('src',oldSrc + '?'); // 問號會重新發送一次請求
})
}
views.py:
def login(request):
if request.method == 'GET':
form = LoginForm(request)
return render(request, 'user/login.html', dict(form=form))
else:
form = LoginForm(request, data=request.POST)
if form.is_valid():
return JsonResponse(dict(status=True, path=reverse('index')))
else:
return JsonResponse(dict(status=False, error_msg=form.errors))
form校驗類:
from django import forms
from django.core.exceptions import ValidationError
from django.db.models import Q
from web import models
from web.utils.bootstrap_style import BootStrapForm
from web.utils.enc import set_md5
class LoginForm(BootStrapForm, forms.Form):
'''手機號或者郵箱登錄'''
username = forms.CharField(label='手機號或者郵箱')
password = forms.CharField(widget=forms.PasswordInput, label='密碼')
image_code = forms.CharField(label='驗證碼')
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
def clean_password(self):
'''密碼加密傳輸'''
password = self.cleaned_data.get('password')
return set_md5(password)
def clean_image_code(self):
'''驗證圖片驗證碼 * 用戶輸入的和後台保存的要一致 '''
user_code = self.cleaned_data.get('image_code', '')
session_code = self.request.session.get('image_code', '')
if not session_code:
raise ValidationError('驗證碼已經過期!!')
if user_code.strip().upper() != session_code.upper():
raise ValidationError('驗證碼錯誤!!!')
return session_code
def clean(self):
'''手機號郵箱校驗'''
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
uname_or_email = models.UserInfo.objects.filter(
Q(Q(phone=username)| Q(email=username)),
password=password
).exists()
if not uname_or_email:
self.add_error('username','用戶名或密碼錯誤!!')
return self.cleaned_data