前言
在提交表单的时候为了防止机器操作或者是恶意的攻击,在填写表单的时候一般都用验证码来过滤掉一些非法提交数据。今天给大家介绍一款超实用超漂亮的Python验证码库:KgCaptcha。

前端接入代码
1<script src="captcha.js?appid=xxx"></script> 2<script> 3kg.captcha({ 4 // 绑定元素,验证框显示区域 5 bind: "#captchaBox", 6 7 // 验证成功事务处理 8 success: function(e) { 9 console.log(e); 10 }, 11 12 // 验证失败事务处理 13 failure: function(e) { 14 console.log(e); 15 }, 16 17 // 点击刷新按钮时触发 18 refresh: function(e) { 19 console.log(e); 20 } 21}); 22</script> 23 24<div id="captchaBox"></div>
Python 接入代码
1from wsgiref.simple_server import make_server 2from KgCaptchaSDK import KgCaptcha 3 4def start(environ, response): 5 # 填写你的 AppId,在应用管理中获取 6 AppID = "AppID" 7 # 填写你的 AppSecret,在应用管理中获取 8 AppSecret = "AppSecret" 9 10 request = KgCaptcha(AppID, AppSecret) 11 12 # 填写应用服务域名,在应用管理中获取 13 request.appCdn = "https://cdn.kgcaptcha.com" 14 15 # 请求超时时间,秒 16 request.connectTimeout = 10 17 18 # 用户id/登录名/手机号等信息,当安全策略中的防控等级为3时必须填写 19 request.userId = "kgCaptchaDemo" 20 21 # 使用其它 WEB 框架时请删除 request.parse,使用框架提供的方法获取以下相关参数 22 parseEnviron = request.parse(environ) 23 # 前端验证成功后颁发的 token,有效期为两分钟 24 request.token = parseEnviron["post"].get("kgCaptchaToken", "") # 前端 _POST["kgCaptchaToken"] 25 # 客户端IP地址 26 request.clientIp = parseEnviron["ip"] 27 # 客户端浏览器信息 28 request.clientBrowser = parseEnviron["browser"] 29 # 来路域名 30 request.domain = parseEnviron["domain"] 31 32 # 发送请求 33 requestResult = request.sendRequest() 34 if requestResult.code == 0: 35 # 验证通过逻辑处理 36 html = "验证通过" 37 else: 38 # 验证失败逻辑处理 39 html = f"{requestResult.msg} - {requestResult.code}" 40 41 response("200 OK", [("Content-type", "text/html; charset=utf-8")]) 42 return [bytes(str(html), encoding="utf-8")] 43 44 45httpd = make_server("0.0.0.0", 8088, start) # 设置调试端口 46httpd.serve_forever()
最后
SDK开源地址:https://github.com/KgCaptcha,顺便做了一个演示:https://www.kgcaptcha.com/demo/
