django中的图片验证码功能
作者:↘妳是我の半途ёг廢√ 时间:2022-06-10 00:07:54
python的验证码库(captcha)
将验证码做成这样:
是不是和各大网页的图片源地址是一样,话不多说,让我们看代码:
我是用django和python中的captcha库做成 的
创建一个captcha_image.py:
from captcha.image import ImageCaptcha
import random
class Captcha_Get():
def __init__(self,
CHAR_SET = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
CAPTCHA_LEN = 4):
self.CHAR_SET = CHAR_SET
self.CAPTCHA_LEN = CAPTCHA_LEN
def get_captcha(self):
captcha_list = []
for i in range(self.CAPTCHA_LEN):
random_choice = random.choice(self.CHAR_SET)
captcha_list.append(random_choice)
return captcha_list
def get_captcha_image(self):
image = ImageCaptcha()
captcha_list = self.get_captcha()#返回一个列表
captcha_str = ''.join(captcha_list)#将列表的所有内容整合成一个字符串
captcha_image = image.generate(captcha_str)
#captcha_image返回<_io.BytesIO object at 0x000001C8758C8728>,它是一个<class '_io.BytesIO'>
return captcha_str,captcha_image#因为要和django登陆相结合所以验证码的内容也要返回
然后,创建django项目
python-admin startproject mysite
创建app
python manage.py startapp app
在setting文件 * 册app,写好urls,将captcha_image文件放入app目录下
views.py:
from django.http import JsonResponse,HttpResponse
from .captcha_image import *
def auth_code_port(request):
"""
生成验证码的接口
:param request:
:return: 图片的对象
"""
captcha_str, image_64 = Captcha_Get().get_captcha_image()
#request.session['captcha_str'] = captcha_str #将验证码内容放入session以便于后边判断,但必须迁移数据库,否则报错
#image = 'data:image/png;base64,'+image_64
resp = HttpResponse(image_64, content_type='image/png')
return resp
让我测试一下验证码接口是否正确:运行django项目,然后在网页上输入127.0.0.1:8000/app/auth_code_port
这样就好了,在前端模板中就可以直接调用接口。
总结
以上所述是小编给大家介绍的django中的图片验证码功能,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://blog.csdn.net/weixin_44482817/article/details/88869516
标签:django,验证码
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
自适应内容高度的收缩与展开
2007-09-24 14:38:00
python实现多线程暴力破解登陆路由器功能代码分享
2023-08-28 21:27:01
SQL Server从安装到建库为新手寻找捷径
2009-01-13 13:22:00
网站重构到底是什么
2008-11-03 11:30:00
简单介绍一下pyinstaller打包以及安全性的实现
2021-07-23 15:34:56
![](https://img.aspxhome.com/file/2023/8/78718_0s.png)
Python基础知识学习之类的继承
2022-09-02 15:41:05
Python实现字符串格式化输出的方法详解
2023-05-02 20:52:59
详解python 一维、二维列表的初始化问题
2023-01-21 06:57:31
PHP实现断点续传乱序合并文件的方法
2023-06-20 02:35:21
Django自定义分页效果
2023-12-06 00:09:04
![](https://img.aspxhome.com/file/2023/1/84001_0s.png)
mysql 各种时间段查询
2010-01-06 13:37:00
python中dict()的高级用法实现
2022-06-16 23:24:29
![](https://img.aspxhome.com/file/2023/2/84122_0s.png)
PHP的PDO事务与自动提交
2023-06-09 02:32:55
如何让shell终端和goland控制台输出彩色的文字
2023-07-13 03:24:56
![](https://img.aspxhome.com/file/2023/9/87629_0s.jpg)
Python中非常实用的Math模块函数教程详解
2022-12-08 02:12:49
MySQL Dump/Restore
2010-10-14 13:49:00
tensorflow转onnx的实现方法
2022-07-08 23:04:51
如何使用python爬取知乎热榜Top50数据
2021-11-13 05:47:09
![](https://img.aspxhome.com/file/2023/5/81775_0s.png)
解决SQLServer最大流水号的两个好方法
2009-01-13 14:15:00
十行代码使用Python写一个USB病毒
2021-08-27 17:05:41
![](https://img.aspxhome.com/file/2023/3/69593_0s.jpg)