BBS登录功能
一、后端实现
1.实现验证码
from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO, StringIO
def get_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
def get_code(request):
'图片验证'
# img:标签支持1.图片二进制 2. 图片具体路径 3. 后端url请求
# 推到思路1: 直接到后端获取目录下的路径,以二进制方式打开发送
# with open(r'G:python学习Django11Django项目BBSstaticimg1.jpg', 'rb') as f:
# data = f.read()
#
# return HttpResponse(data)
# 推到思路二: 利用模块产生图片, 在发送到前端 pillow
# 1.生成一张图片对象
# img_obj = Image.new('RGB', (260, 35), get_color())
#
# # 2.先利用文件操作将图片对象写入文件中
# with open('code.png', 'wb') as f:
# img_obj.save(f, 'png')
#
# # 3. 在利用文件操作图片以二进制形式读取出来,返回给前端
# with open('code.png', 'rb') as f:
# data = f.read()
#
# return HttpResponse(data)
# 推到思路3: 不在利用文件获取数据 借助内存管理器
# 1. 生成图片对象
# img_obj = Image.new('RGB', (260, 35), get_color())
# # 2. 生成一个内存管理器对象
# io_obj = BytesIO()
#
# # 3.将io_obj当成文件句柄f
# img_obj.save(io_obj, 'png')
#
# # 4 获取二进制图片发送给前端
# return HttpResponse(io_obj.getvalue())
# 推导思路四:在图片写入文字
# 1. 生成图片对象
img_obj = Image.new('RGB', (260, 35), get_color())
# 2.生成一个画笔对象
img_draw = ImageDraw.Draw(img_obj)
# 3. 设置画笔字体样式(所有字体样式都是由.ttf结尾的文件控制)
img_font = ImageFont.truetype(r'G:python学习Django11Django项目BBSstaticfont222.ttf', 30)
# 生成随机验证码
code = ''
# 随机生成验证码 a~z A~Z 0~9
for i in range(5):
random_upper = chr(random.randint(65, 90))
random_lower = chr(random.randint(97, 122))
random_int = str(random.randint(0, 9))
res = random.choice([random_upper, random_lower, random_int])
# 将产生的随机字符串写到图片上
img_draw.text((i * 45 + 45, 0), res, get_color(), img_font)
code += res
print(code)
# 将随机验证码存储起来, 以便其他函数调用
request.session['code'] = code
io_obj = BytesIO()
img_obj.save(io_obj, 'png')
return HttpResponse(io_obj.getvalue())
二、登录功能实现
def login(request):
back_dic = {'code': 1000, 'msg': ""}
if request.method == 'POST':
print(request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('code').upper()
session_code = request.session.get('code').upper()
if code == session_code:
user_obj = auth.authenticate(username=username, password=password)
if user_obj:
back_dic['url'] = '/index/'
# 保存用户登录状态
auth.login(request, user_obj) # 自动保存到session
else:
back_dic['code'] = ''
back_dic['msg'] = '用户名或密码错误!'
else:
back_dic['code'] = ''
back_dic['msg'] = '验证码错误!'
return JsonResponse(back_dic)
return render(request, '02login.html')
二、前端设计
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'bootstrap/js/jquery.js' %}"></script>
<script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.css' %}">
</head>
<body>
<div class="container">
<div class="row">
<h1 class="text-center">登录界面</h1>
<div class="col-md-6 col-lg-offset-3">
<div class="form-group">
<label for="username"> 用户名</label>
<input type="text" id='username' name="username" class="form-control">
</div>
<div class="form-group">
<label for="password"> 密 码: </label>
<input type="password" id='password' name="password" class="form-control">
</div>
<div class="form-group">
<label for="">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" id='code' name='code' class="form-control">
</div>
<div class="col-md-6">
<img src="/get_code/" alt="" width="260px" height="35px" class="img-rounded">
</div>
</div>
</div>
<div>
{# <input type="reset" value="重置" class="btn btn-primary btn-sm" style="margin: 10px 35px">#}
<button class="btn btn-primary" id="b1">登录</button>
<span style="color:red" id="error"></span>
</div>
</div>
</div>
</div>
<script>
// 点击图片刷新验证码
$('img').on('click', function () {
var img_url = $(this).attr('src') + "?";
$(this).attr('src', img_url);
});
$('#b1').click(function () {
alert(234);
// 登录验证
$.ajax({
url: '',
type: 'post',
data: {
'username': $('#username').val(),
'password': $("#password").val(),
'code': $('#code').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data) {
if (data.code == 1000) {
// 成功进入首页
location.href = data.url
} else {
// 渲染错误信息
$('#error').text(data.msg);
// 失败刷新验证码
$('img').attr('src', '/get_code/2');
}
}
});
});
</script>
</body>
</html>