【问题标题】:Flask session not passing to different function烧瓶会话没有传递给不同的功能
【发布时间】:2020-11-27 22:05:31
【问题描述】:

我有两个功能:

@app.route('/firstfunc', methods = ['POST'])
def firstfunc():
        session['final_box'] = 10
        session.modified = True
        return jsonify("success")
    return jsonify("error")

@app.route('/secondfunc', methods = ['GET','POST'])
def secondfunc():
    if request.method == 'POST':
        final_boxx = session['final_box']
        print("VALUE----------------------->>>>>>", session['final_box'])
    return render_template('some.html', final_boxx = final_boxx)

AJAX 调用:

$.ajax({
            type: "POST",
            cache: false,
            data:{data:annotation_Jsonstringify,image_height:realHeight,image_width:realWidth,image_name:filename},
            url: "/firstfunc",
            dataType: "json",
            success: function(data) {
                alert(data);
              return true;  
            }
        

    });

会话变量通过 Ajax 发送。提交表单后,当我尝试访问会话变量时,我收到此错误消息。

错误:

in __getitem__ return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'final_box'

我在这个平台上遇到过许多类似的问题。没有一个适合这个案例。
我已经尝试过的:

  1. session.modified=会话后为真['final_box']=final_box
  2. app.secret_key 已经存在
  3. 等待所有待处理的请求在服务器端完成

对解决方案的任何指示或轻推表示赞赏。

【问题讨论】:

    标签: ajax session flask flask-session


    【解决方案1】:

    此错误是因为尝试将 numpy 数组传递为 JSON 格式。内置的 python json 模块可以序列化常用的 python 数据结构,但不能对 Numpy 数组做同样的事情。为此,我们需要使用自定义 json 编码器。

    from json import JSONEncoder
    
    class NumpyArrayEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, numpy.ndarray):
                return obj.tolist()
            return JSONEncoder.default(self, obj)
    
    numpyArrayOne = numpy.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
    
    # Serialization
    numpyData = {"array": numpyArrayOne}
    encodedNumpyData = json.dumps(numpyData, cls=NumpyArrayEncoder) 
    
    # Deserialization
    decodedArrays = json.loads(encodedNumpyData)
    

    这样,作为图像数组的 final_box 可以作为会话跨函数发送。

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2018-08-18
      相关资源
      最近更新 更多