(365)
(8)
(130)
(155)
(50)
(22)
分类: python/ruby
2021-08-19 17:24:03
工具类代码
# coding=utf-8
import random
from io import bytesio
from pil import image,imagefont,imagedraw
def getcode():
source = 'qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm1234567890'
code = ""
for i in range(4):
code = random.choice(source)
return code
def set_color():
return random.randrange(255)
def send_code_img(request):
color_bg = (set_color(), set_color(), set_color())
image = image.new("rgb", size=(150, 50), color=color_bg)
imagedraw = imagedraw.draw(image, "rgb")
font = imagefont.truetype("/static/font/alger.ttf", 55)
yanzhen_code = getcode()
imagedraw.text(xy=(0, 0), text=yanzhen_code, font=font, fill=(255, 255, 255))
request.session["verify_code"]=yanzhen_code
for i in range(800):
# 绘制干扰点
imagedraw.point(xy=(random.randrange(150), random.randrange(50)), fill=(set_color(), set_color(), set_color()))
# image.show()
fp = bytesio()
image.save(fp,"png")
return fp.getvalue()
if __name__=="__main__":
pass
views的代码
from django.http import httpresponse, httpresponseredirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from app.tools.yanzhen import send_code_img
def mine(request):
return httpresponse("欢迎登录")
@csrf_exempt
def login(request):
if request.method == "get":
return render(request, "yanzhen.html")
elif request.method == "post":
post_code = request.post.get("get_code")
verify_code = request.session.get("verify_code")
if post_code.lower() != verify_code.lower():
return redirect(reverse("app:login"))
return redirect(reverse("app:mine"))
def get_code_img(request):
code_img = send_code_img(request)
return httpresponse(code_img, content_type='image/png')
html代码
{% load static %}
上一篇:
下一篇: