def create_captcha(request): hashkey = CaptchaStore.generate_key() # 生成hashkey imgage = captcha_image(request, hashkey) # 将图片转换为base64 image_base = base64.b64encode(imgage.content) print(hashkey) captcha = {'hashkey': hashkey, 'image_url': image_base.decode('utf-8')} return captcha
def get(self, request): hashkey = CaptchaStore.generate_key() try: # 获取图片id id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id image = captcha_image(request, hashkey) # 将图片转换为base64 字节类型的数据,需要解码成字符串 image_base = base64.b64encode(image.content) data = {"id": id_, "image": image_base.decode("utf-8")} return Response({"code": 1000, "data": data, "message": None}) except: return Response({"code": 1001, "data": None, "message": "请求失败"})
def list(self, request, *args, **kwargs): hashkey = CaptchaStore.generate_key() try: #获取图片id id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id imgage = captcha_image(request, hashkey) #将图片转换为base64 image_base = base64.b64encode(imgage.content) json_data = json.dumps({"codeId": id_, "image": "data:image/png;base64,"+image_base.decode('utf-8')}) except: json_data = None return HttpResponse(json_data, content_type="application/json")
def post(self, request, format=None): key = CaptchaStore.generate_key() image = base64.b64encode(captcha_image(request, key).content) serializer = AccountCaptchaGetSerializer(data={ "key": key, "image": image.decode() }) if serializer.is_valid(): return Response(data=serializer.data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get(self, request): ''' 获取图片验证码 :param request: :return: ''' hashkey = CaptchaStore.generate_key() _id = CaptchaStore.objects.filter(hashkey=hashkey).first().id image = captcha_image(request, hashkey) # 将图片转换为base64 image_base = base64.b64encode(image.content) data = {"id": _id, "image_base": image_base.decode('utf-8'), "type": "image/png", "encoding": "base64"} return ApiResponse(data, code=200, msg='ok', status=status.HTTP_201_CREATED)
def get(self, request): hashkey = CaptchaStore.generate_key() try: # 获取id id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id image = captcha_image(request, hashkey) # captcha_image内部是用get获取,需要加异常 # base64加密 image_base = base64.b64encode(image.content) # json_data = json.dumps({"id":id_,"image_base64":image_base.decode('utf-8')}) json_data = {"id": id_, "image_base64": image_base.decode('utf-8')} except: json_data = None return Response(json_data)