Python一键生成验证码并部署(django)
工具类代码
coding=utf-8
【Python一键生成验证码并部署(django)】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 =[PerfectMoney下载](https://www.gendan5.com/wallet/PerfectMoney.html) 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 %}
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)
- 记录iOS生成分享图片的一些问题,根据UIView生成固定尺寸的分享图片