图片验证码

1. 图形验证码接口设计

1.请求方式

选项方案
请求方法 GET
请求地址 image_codes/(?P<uuid>[\w-]+)/

2.请求参数:路径参数

参数名类型是否必传说明
uuid string 唯一编号

3.响应结果:image/jpg

2. 图形验证码接口定义

1.图形验证码视图

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        pass

  

2.总路由

# verifications
url(r'^', include('verifications.urls')),

  

3.子路由

# 图形验证码
url(r'^image_codes/(?P<uuid>[\w-]+)/$', views.ImageCodeView.as_view()),

 

准备Redis的2号库存储验证码数据

"verify_code": { # 验证码
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },

图形验证码后端逻辑实现

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpg')

 


posted @ 2021-05-17 21:14  lcsp  阅读(330)  评论(0编辑  收藏  举报