Py学习  »  Python

Python-web验证码的实现

马哥Linux运维 • 4 年前 • 409 次点击  

马哥Python网络班学员问题:能否说下web验证的原理,感觉文字描述不清楚,

此代码是需要依赖:

  • sanic==19.9.0

  • Pillow==7.0.0

马哥教育Python网络班企业教练思路:

import randomimport stringimport uuidimport base64import platformfrom PIL import Image, ImageDraw,ImageFontfrom io import BytesIOfrom sanic import Sanicfrom sanic.response import HTTPResponse,textfrom sanic.views import HTTPMethodView
app = Sanic()
session = {}
class VerifyCode: def __init__(self, numbers:int): """ 指定:生成的数量 """ self.number = numbers
def draw_lines(self, draw, num, width, height): """划线"""
x1 = random.randint(0, width / 2) y1 = random.randint(0, height / 2) x2 = random.randint(0, width) y2 = random.randint(height / 2, height) draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
def random_color(self): """随机颜色""" return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))    def gene_text(self): """生成验证码""" return "".join(random.sample(string.ascii_letters+string.digits, self.number))
def get_verify_code(self): """ draw.text(): 文字的绘制,第一个参数指定绘制的起始点(文本的左上角所在位置),第二个参数指定文本内容,第三个参数指定文本的颜色,第四个参数指定字体(通过ImageFont类来定义) """ code = self.gene_text() width, height = 130, 30 im = Image.new("RGB ", (width, height), "white") sysstr = platform.system() font = None if sysstr == "Windows": font = ImageFont.truetype("C:\WINDOWS\Fonts\STXINGKA.TTF", 25) elif sysstr == "Darwin": font = ImageFont.truetype('/Library/Fonts/AppleMyungjo.ttf', 25) draw = ImageDraw.Draw(im) for item in range(self.number): draw.text((5+random.randint(-5,5)+23*item, 5+random.randint(-5, 5)), text=code[item], fill=self.random_color(), font=font) self.draw_lines(draw, self.number, width, height) return im, code

class SimpleView(HTTPMethodView): body = """ <html> <head> <meta charset="UTF-8"> <title>登录title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">script> head> <body> <form class="form-inline" method="post" action="/code"> <div> <div class="form-group">{error}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56659
 
409 次点击