django中的图片验证码功能

yipeiwu_com6年前Python基础

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中的图片验证码功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python递归函数定义与用法示例

本文实例讲述了Python递归函数定义与用法。分享给大家供大家参考,具体如下: 递归函数 在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。 举个例子,...

Python实现二维数组输出为图片

对于二维数组,img_mask [[ 0 0 0 ..., 7 7 7] [ 0 0 0 ..., 7 7 7] [ 0 0 0 ..., 7 7 7] ..., [266...

python通过定义一个类实例作为ftp回调方法

本文实例讲述了python通过定义一个类实例作为ftp回调方法。分享给大家供大家参考。具体实现方法如下: class Writer: def __init__(self, fil...

Python使用pymysql模块操作mysql增删改查实例分析

本文实例讲述了Python使用pymysql模块操作mysql增删改查。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import pymysql...

详解python中requirements.txt的一切

简介 Python项目中必须包含一个 requirements.txt 文件,用于记录所有依赖包及其精确的版本号。以便新环境部署。 主要的写法如下所示 pip freeze >...