DRF 图片/语音验证码

倾然丶 夕夏残阳落幕 提交于 2019-11-29 14:00:44

drf 集成图片/语音验证码

基本流程在线图片base64

views 集成

  • 生成url_link (后端重定向到link)
  • base64 png (图片数据, 避免二次请求) urls.py
path('code_img', views.CodeImageView.as_view(), name='code_img'),

serializers.py

class CodeImageSerializer(ModelSerializer):
    id = serializers.IntegerField(label='id', read_only=True)
    link = serializers.SerializerMethodField(help_text='img url')
    image_code_data = serializers.SerializerMethodField(
        help_text='img base64 png')

    @staticmethod
    def get_link(obj):
        return obj.link

    @staticmethod
    def get_image_code_data(obj):
        return obj.image_code_data

    class Meta:
        model = CaptchaStore
        fields = ['id', 'link', 'image_code_data']
class CodeImageView(AllowAnyView):
    serializer_class = CodeImageSerializer

    def get(self, request):
        """
        图片验证码

        ---
        serializer: CodeImgSerializer
        """
        hash_key = CaptchaStore.generate_key()
        obj = CaptchaStore.objects.filter(hashkey=hash_key).first()
        logger.debug(f'CaptchaStore filter hash_key:{hash_key} obj:{obj}')
        if not obj:
            logger.error(f'hash_key:{hash_key} filter is: {obj}')
            return Response(
                make_response(data=None),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        try:
            obj.link = captcha_image_url(hash_key)
            # 将图片转换为base64
            image_code_resp = captcha_image(request, hash_key)
            image_base64 = base64.b64encode(image_code_resp.content)
            image_base64_str = image_base64.decode('utf-8')
            # data:image/png;base64,image_data
            obj.image_code_data = f"data:image/png;base64,{image_base64_str}"
            serializer = self.get_serializer(obj)
            data = serializer.data
        except Exception as e:
            logger.error(f'err:{e}', exc_info=True)
            data = None
        return Response(make_response(data=data))

三方包

simple-captcha 源码

####urls.py 入口

  • 图片验证码
  • 音频验证码
  • 刷新
urlpatterns = [
    url(r'image/(?P<key>\w+)/$', views.captcha_image, name='captcha-image', kwargs={'scale': 1}),
    url(r'image/(?P<key>\w+)@2/$', views.captcha_image, name='captcha-image-2x', kwargs={'scale': 2}), #2倍
    url(r'audio/(?P<key>\w+).wav$', views.captcha_audio, name='captcha-audio'),
    url(r'refresh/$', views.captcha_refresh, name='captcha-refresh'), # 重新生成
]

注意点

views.captcha_refresh 返回:key, 需要通过key查记录找到store.

views.captcha_image 返回图片

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!