Куки не устанавливаются в браузере Django

Я делаю веб-приложение на Django и Electron, используя websockets, и я хотел вставить один из ответов сокета в cookies пользователя, но, к сожалению, я не знаю почему, но они не вставляются, вот пример того, что я делаю:

В распечатке response.cookies появляется что-то вроде этого: Cookies defined in the response: Set-Cookie: image_data="pls work"; expires=Tue, 21 May 2024 16:22:33 GMT; Max-Age=3600; Path=/

Вот мой код, если у вас есть какие-либо идеи или вам нужна какая-либо часть кода, я предоставлю ее, спасибо.

code:

@csrf_exempt
def process_screenshot(request):
    call = identificador_unico(request)
    print("call:", call)
    if request.method == 'POST':
        image_content = request.POST.get('image_content')
        
        if image_content:
            print("String em base64 recebida com sucesso.")
            try:
                # Decodifica a string em base64 para obter os dados binários da imagem
                image_data = base64.b64decode(image_content)
                print("base64", image_data[:20])
                
                # Salva os dados binários da imagem em um arquivo
                file_path = 'frames/screenshot.jpg'
                with open(file_path, 'wb') as f:
                    f.write(image_data)
                
                image_content = "pls work"
                # Salva image_data nos cookies
                response = JsonResponse({'message': 'Imagem processada com sucesso'})
                response.set_cookie('image_data', image_content, max_age=3600,secure=False,samesite=None)  # Expira em 1 hora
                print("Cookies definidos na resposta:", response.cookies)
                
                return response
            except Exception as e:
                # Se ocorrer algum erro ao decodificar a string em base64 ou salvar o arquivo
                print("Erro ao processar imagem:", e)
                return JsonResponse({'error': 'Erro ao processar imagem'}, status=500)
        else:
            # Se nenhuma string em base64 for recebida
            print("Nenhuma string em base64 recebida.")
            return JsonResponse({'error': 'Nenhuma string em base64 recebida'}, status=400)
    else:
        # Se a solicitação não for do tipo POST
        return JsonResponse({'error': 'Método não permitido'}, status=405)

экран cookies в браузере:

enter image description here

Существует проблема с тем, как вы устанавливаете Cookie в process_screenshot(). Если атрибут SameSite в Cookie установлен на None, то это требует безопасного контекста, то есть Cookie должен иметь атрибут Secure. Здесь вы нарушаете этот принцип:

response.set_cookie('image_data', image_content, max_age=3600, samesite=None, secure=False)

Измените его на этот, и он будет работать:

response.set_cookie('image_data', image_content, max_age=3600, samesite=None, secure=True)
Вернуться на верх