from captcha.models import CaptchaStore
from asgiref.sync import sync_to_async
from django.http import JsonResponse


def is_ajax(request):
    return request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"


@sync_to_async
def ajax_captcha(request):
    if is_ajax(request=request):
        cs = CaptchaStore.objects.filter(response=request.GET["response"],
                                         hashkey=request.GET["hashkey"])
        if cs:
            json_data = {"status": 1}
        else:
            json_data = {"status": 0}
        return JsonResponse(json_data)
    else:
        # raise Http404
        json_data = {"status": 404}
        return JsonResponse(
            json_data)  # 需要导入  from django.http import JsonResponse
