You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中部分接口无法在浏览器设置Cookie问题排查求助

问题排查请求

我使用Django和Electron开发一款基于WebSocket的Web应用,想要将Socket响应内容存入用户浏览器的Cookie中,但发现process_screenshot接口设置的Cookie无法被浏览器写入。虽然后端打印的响应中包含Set-Cookie头(如:Set-Cookie: image_data="pls work"; expires=Tue, 21 May 2024 16:22:33 GMT; Max-Age=3600; Path=/),但浏览器中看不到该Cookie;而另一接口process_frame的Cookie设置却能正常生效。请求帮忙排查原因:

问题代码

@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("Base64字符串接收成功。")
            try:
                # 解码Base64字符串获取图片二进制数据
                image_data = base64.b64decode(image_content)
                print("base64数据片段:", image_data[:20])
                
                # 将图片二进制数据保存到文件
                file_path = 'frames/screenshot.jpg'
                with open(file_path, 'wb') as f:
                    f.write(image_data)
                
                image_content = "pls work"
                # 将image_data存入Cookie
                response = JsonResponse({'message': '图片处理成功'})
                response.set_cookie('image_data', image_content, max_age=3600, secure=False, samesite=None)  # 1小时后过期
                print("响应中设置的Cookie:", response.cookies)
                
                return response
            except Exception as e:
                # 解码Base64或保存文件时出错
                print("图片处理错误:", e)
                return JsonResponse({'error': '图片处理失败'}, status=500)
        else:
            # 未接收到Base64字符串
            print("未接收到Base64字符串。")
            return JsonResponse({'error': '未接收到Base64字符串'}, status=400)
    else:
        # 请求方法非POST
        return JsonResponse({'error': '不允许的请求方法'}, status=405)

浏览器Cookie截图

浏览器Cookie截图

正常生效的代码

@csrf_exempt
def process_frame(request):
    print("处理帧数据...")
    if request.method == 'POST':
        frame_data = request.POST.get('frame_data')
        frame_data = frame_data.split(',')[1]  # 移除前缀'data:image/png;base64,'
        frame_data = base64.b64decode(frame_data)
        frame_data = np.frombuffer(frame_data, dtype=np.uint8)
        frame = cv2.imdecode(frame_data, flags=1)

        cv2.imwrite('frames/CurrentFrame.jpg', frame)
        
        # 将帧数据传入compare_faces函数
        result = compare_faces(request, frame)
        print("比对结果:", result)
        if result is None:
            response = JsonResponse({'error': '未找到用户,请录入人脸'}, status=400)
        elif isinstance(result, HttpResponseRedirect):
            response = JsonResponse({'message': '跳转', 'url': result.url})
        else:
            response = JsonResponse({'message': result})

        # 如果生成了UUID,将其存入响应Cookie
        face_recognition = FaceRecognition(request)
        if face_recognition.uuid is not None:
            print("处理帧时生成的UUID:", face_recognition.uuid)
            response.set_cookie('user_uuid', str(face_recognition.uuid))

        print("响应内容:", response)
        return response
    else:
        return JsonResponse({'message': '不允许的请求方法'}, status=405)

排查方向

  • SameSite属性冲突:process_screenshot中设置了samesite=None,但同时指定secure=False。现代浏览器要求samesite=None的Cookie必须搭配secure=True(即使本地开发,Electron的Web环境也可能遵循该规则)。而process_frame未显式设置SameSite,默认值为Lax,无需Secure即可生效。
  • 请求触发方式差异:确认两个接口的请求发起渠道——process_screenshot是否通过WebSocket触发,而process_frame是普通HTTP请求?WebSocket响应的Set-Cookie头在Electron中可能被浏览器安全策略拦截,和普通HTTP请求的Cookie处理逻辑不同。
  • Electron会话配置:检查Electron主进程的session设置,比如是否启用了第三方Cookie限制,或webPreferences中的partition、allowFileAccess等选项影响了Cookie存储权限。

内容的提问来源于stack exchange,提问作者André Pimentel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 20:34:54