首页 / PYTHON / Python-web验证码的实现
Python-web验证码的实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python-web验证码的实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5016字,纯文字阅读大概需要8分钟。
内容图文
![Python-web验证码的实现](/upload/InfoBanner/zyjiaocheng/599/a6a809db9d464d43ba67909c04011fa6.jpg)
此代码是需要依赖:
sanic==19.9.0
Pillow==7.0.0
马哥教育Python网络班企业教练思路:
import random
import string
import uuid
import base64
import platform
from PIL import Image, ImageDraw,ImageFont
from io import BytesIO
from sanic import Sanic
from sanic.response import HTTPResponse,text
from 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">
? ? ? ? ? ? ? ? ? ?<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
? ? ? ? ? ? ? ? ? ?<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">
? ? ? ? ? ? ? ? ? ?<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
? ? ? ? ? ? ? ? ? ?<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} ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ? ? ? ? ?<div class="form-group">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<label for="exampleInputName2">验证码</label>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<input type="text" class="form-control" id="captcha" name="code">
? ? ? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ? ? ? ? ?<div class="form-group">
? ? ? ? ? ? ? ? ? ? ? ? ? ?<img src="data:image/jpeg;base64,{base64_data}" class="img-img-rounded">
? ? ? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ? ? ? ? ?<div>
? ? ? ? ? ? ? ? ? ? ? ? ? ?<button type="submit">验证</button>
? ? ? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ? ? ?</div>
? ? ? ? ? ? ? ?</form>
? ? ? ? ? ?</body>
? ? ? ?</html>
? ? ? ?"""
? ?async def get(self, request):
? ? ? ?return self.response(error="")
? ?async def post(self, request):
? ? ? ?uuid = request.cookies.get("uuid", "1")
? ? ? ?verfy_code = request.form.get("code", "2").lower()
? ? ? ?code = session.get(uuid, "").lower()
? ? ? ?if code == verfy_code:
? ? ? ? ? ?return text('验证码正确')
? ? ? ?return self.response(error='<input class="form-control" id="disabledInput" type="text" placeholder="验证码错误" disabled>')
? ?def response(self, error):
? ? ? ?im, code = VerifyCode(5).get_verify_code()
? ? ? ?buf = BytesIO()
? ? ? ?im.save(buf, "jpeg")
? ? ? ?buf_str = buf.getvalue()
? ? ? ?base64_data = base64.b64encode(buf_str).decode()
? ? ? ?id = uuid.uuid1().__str__()
? ? ? ?session[id] = code
? ? ? ?body = self.body.format(base64_data=base64_data, error=error)
? ? ? ?response = HTTPResponse(body, content_type="text/html; charset=utf-8")
? ? ? ?response.cookies["uuid"] = id
? ? ? ?return response
app.add_route(SimpleView.as_view(), '/code')
if __name__ == "__main__":
? ?app.run(host="0.0.0.0", port=8000)
简单的实现了验证码,没有实现点击刷新,点击刷新的原理不难:
异步请求+刷新接口就好了,记得更新对应的session的key里面的value
内容总结
以上是互联网集市为您收集整理的Python-web验证码的实现全部内容,希望文章能够帮你解决Python-web验证码的实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。