【DJango项目】第一章 验证码

我们现在在工程目录/meiduo_mall/apps中创建Django应用users,并在配置文件中注册users应用。

python manage.py startapp users  ---->  INSTALL_APPS注册

class User(AbstractUser):
    """用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

在配置文件中配置 

AUTH_USER_MODEL = 'users.User'

执行数据库迁移

python manage.py makemigrations
python manage.py migrate

图片验证码

python manage.py startapp verifications   ---->  INSTALL_APPS注册

setting.py

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

urls.py

urlpatterns = [
    url(r'image_codes/(?P<image_code_id>\d+)$', views.ImangeCodeView.as_view()),
]

constants.py

# 图片验证码有效期 单位秒
IMAGE_CODE_REDIS_EXPIRES = 300

view.py

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.views import APIView

# Create your views here.
from meiduo_mall.libs.captcha.captcha import captcha
from verifications import constants


class ImangeCodeView(APIView):
    """
    图片验证码
    """

    def get(self, request, image_code_id):
        # 生成验证码图片
        text, image = captcha.generate_captcha()
     # 获取redis数据库地址 
        redis_conn = get_redis_connection("verify_codes")
# 存入redis数据库 redis_conn.setex(
"img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)      # 返回数据到前端 return HttpResponse(image, content_type="images/jpg")

请求方式:GET /image_code/<image_code_id>/

                  传入 image_code_id 图片验证码编号 

返回内容 :返回图片文件 

猜你喜欢

转载自www.cnblogs.com/oscarli/p/12356737.html
今日推荐