django实现图片验证码加载

django图片验证码的加载

  • 1.新建用于验证的app,verifications
    在apps文件夹下创建app,verifications
../ python manage.py startapp verifications

在这里插入图片描述

  • 2.下载生成验证码的python模块
    在这里插入图片描述
  • 3.配置类视图
import logging
from django.views import View
from django.http import HttpResponse
from utils.captcha.captcha import captcha
# Create your views here.
logger = logging.getLogger('django')


class ImageCode(View):
    """
    define image_code verification view
    # /image_codes/<uuid:image_code_id>/
    """
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        return HttpResponse(content=image, content_type="image/jpg")
  • 4.配置urlpatterns
from django.urls import path, re_path
from verifications import views

app_name = 'verifications'
urlpatterns = [
    path('image_codes/<uuid:image_code_id>', views.ImageCode.as_view(), name='image_code'),
]
  • 5.下载生成uuid的js文件
    在这里插入图片描述
  • 6.在模板register.html里面引入生成uuid的js文件
    这个模板继承了基础模板,引入js如下
{% block js %}
    <script src="{% static 'js/users/auth.js' %}"></script>
{% endblock %}
  • 运行项目后结果如下
    在这里插入图片描述
    点击验证码会再新的验证码,如下图
    在这里插入图片描述
    因为用户注册时要验证用户输入的验证码,所以要将验证码的答案保存。

  • 连接redis数据库

CACHES = {
	"default": {
	    "BACKEND": "django_redis.cache.RedisCache",
	    "LOCATION": "redis://127.0.0.1:6379/0",
	    "OPTIONS": {
	        "CLIENT_CLASS": "django_redis.client.DefaultClient",
	    }
	},
	"session": {
	    "BACKEND": "django_redis.cache.RedisCache",
	    "LOCATION": "redis://127.0.0.1:6379/1",
	    "OPTIONS": {
	        "CLIENT_CLASS": "django_redis.client.DefaultClient",
	    }
	},
	"verify_codes": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
}

配置好了数据库就要配置类视图函数了

def get(self, request, image_code_id):
    text, image = captcha.generate_captcha()
    conn_redis = get_redis_connection('verify_codes') #连接redis数据库
    image_key = "img_{}".format(image_code_id) #拼接image_key
    conn_redis.setex(image_key, 300, text) #image_key的保存时间为300秒
    return HttpResponse(content=image, content_type="image/jpg")

然后在前端页面刷新新的图片验证码,在进入redis数据库里面查看

redis-cli
select 2
keys *
在这里插入图片描述

完成!!!

猜你喜欢

转载自blog.csdn.net/xizhao_tianzhao/article/details/89364041