图片验证码

图片验证码

1. 后端接口设计:

访问方式: GET /image_codes/(?P<image_code_id>[\w-]+)/

请求参数: 路径参数

参数类型是否必须说明
image_code_id uuid字符串 图片验证码编号

返回数据:

验证码图片

视图原型
# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()), 
class ImageCodeView(APIView):
    """
    图片验证码
    """
    pass

2. 具体视图实现

在verifications/views.py中实现视图

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

    def get(self, request, image_code_id):
        """
        获取图片验证码
        """
        # 生成验证码图片
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 固定返回验证码图片数据,不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="images/jpg")

说明:

django-redis提供了get_redis_connection的方法,通过调用get_redis_connection方法传递redis的配置名称可获取到redis的连接对象,通过redis连接对象可以执行redis命令。

我们需要在配置文件中添加一个新的redis配置,用于存放验证码数据

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://10.211.55.5:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://10.211.55.5:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "verify_codes": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://10.211.55.5:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
posted @ 2018-07-29 11:11  程序视界  阅读(414)  评论(0编辑  收藏  举报