[Django] Use captcha to generate a graphic verification code and set the validity period

Generally, the login interface will have a graphic verification code. We can use the third-party module captcha to quickly generate a graphic verification code and return it to the front end, and save the correct text to the Redis database

1.captcha

First download the captcha, I have uploaded it to the Baidu network disk, you can download the captcha to use , extraction code: mxum
after downloading, decompress, get a captcha file, we copy it to the project folder

The module is very simple to use, just import the captcha.py file, and then call the generate_captcha() method to generate a four-digit verification code image in jpg format

from XXXXXX.captcha.captcha import captcha
text, image = captcha.generate_captcha()

2. Configure Redis database

Add the storage information of the Redis database in the CACHES dictionary of the configuration file. We store the verification code text in the No. 2 library. The library alias is verify_code. This alias will be used to retrieve data later

CACHES = {
    
    
	...
    # 验证码信息: 存到 2 号库
    "verify_code": {
    
    
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
    
    
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },

}

3. Store to Redis and set the validity period

We save the generated verification code text in the Redis database and return the picture to the front end. The front end must request the verification code within a certain period of time, otherwise it will become invalid

verification.views.py

from django.views import View
from django  import http
from django_redis import get_redis_connection
from XXXXXX.captcha.captcha import captcha

class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成图形验证码
        text, image = captcha.generate_captcha()
        # 使用配置的redis数据库的别名,创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # redis_conn.setex('key', '过期时间', 'value')
        redis_conn.setex('img_%s' % uuid, 300, text) # 有效时间是300秒
        # 响应图形验证码: image/jpg
        return http.HttpResponse(image, content_type='image/jpg')

Set total routing and sub routing

meiduo_mall.urls.py

urlpatterns = [
    ...
    path(r'', include('apps.verifications.urls')),
]

verification.urls.py

urlpatterns = [
	...
	path('image_codes/<uuid:uuid>/', views.ImageCodeView.as_view()),
]

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108408899