Flask-TypeError:类型为cycle的对象不可JSON序列化 [英] Flask - TypeError: Object of type cycle is not JSON serializable

查看:83
本文介绍了Flask-TypeError:类型为cycle的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在客户端通过AJAX发布帖子之后,我正在尝试从服务器向客户端返回json响应.

I'm trying to return a json response from server to client after client makes a post via AJAX.

就像这样,它有效:

@app.route("/test", methods=["GET", "POST"])
@login_required
def test():

  if request.is_xhr:

    try:

      json_response = {
        "result": "success"
      }

    except Exception as e:
      err = _except(line=sys.exc_info()[-1].tb_lineno, error=e, function_name=what_func(), script_name=__file__)
      json_response = {"result": "failure", "msg": err}

    return jsonify(json_response)

  else:
    return redirect("/not-found")

  return ''

如果我这样做,那就行不通了:

If I do like this, it doesn't works:

@app.route("/test", methods=["GET", "POST"])
@login_required
def test():

  if request.is_xhr:

    try:

      _dict = {
        "key1": "value1",
        "key2": "value2"
      }

      if not "my_dict" in session:
        session["my_dict"] = [_dict]
      else:
        session["my_dict"] = session["my_dict"] + [_dict]

      session.modified = True

      json_response = {
        "result": "success"
      }

    except Exception as e:
      err = _except(line=sys.exc_info()[-1].tb_lineno, error=e, function_name=what_func(), script_name=__file__)
      json_response = {"result": "failure", "msg": err}

    return jsonify(json_response)

  else:
    return redirect("/not-found")

  return ''

我收到以下错误,客户端未收到json响应:

I get the following error and client doesn't receives json response:

File "~/myprojectenv/lib/python3.8/site-packages/flask/json/__init__.py", line 100, in default
    return _json.JSONEncoder.default(self, o)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type cycle is not JSON serializable
[2020-09-26 19:01:14,091] ERROR in app: Request finalizing failed with an error while handling an error

如果我取消拉伸:

      if not "my_dict" in session:
        session["my_dict"] = [_dict]
      else:
        session["my_dict"] = session["my_dict"] + [_dict]

      session.modified = True

它再次起作用.客户端收到json响应.

It works again. Client receives json response.

推荐答案

我发现了麻烦.

检查以下功能:

@app.route("/test", methods=["GET", "POST"])
def test():
    if request.is_xhr:
        try:

            licycle = cycle(files)
            nextelem = next(licycle)

            _dict = {
                "sid": session["_id"],
                "licycle": licycle,
                "nextelem": nextelem,
                "licycle2": licycle2,
                "nextelem2": nextelem2,
                "mon_id": _id,
                "sch_id": 0
            }

            if not "all_submons" in session:
                session["all_submons"] = [_dict]
            else:
                session["all_submons"] = session["all_submons"] + [_dict]

            session.modified = True

            all_submons.setdefault("sub_mons", []).append(_dict)

            json_response = {"result": "success"}

        except Exception as e:
            err = _except(line=sys.exc_info()[-1].tb_lineno, error=e, function_name=what_func(), script_name=__file__)
            json_response = {"result": "failure", "err": err}
        finally:
            try:
                print("exiting...")
            except Exception as e:
                pass

        return jsonify(json_response)

    else:
        return redirect("/not-found")

    return ""

原因是licycle变量的类型为< class'itertools.cycle'>会话可能不接受"如您在all_submons dict变量中所见,这种类型的变量(如字典)可以接受.

The reason is that type of licycle variable is <class 'itertools.cycle'> and session "probably doesn't accepts" that type of variable like a dictionary accepts as you can see in my all_submons dict variable.

重点是:

执行不会失败._dict存储在会话中,如下所示.

The execution DOESN'T FALLS in exception. And _dict is stored on session as you can see to next.

print(f"Session before: {session}")
print(f"all_submons before: {all_submons}")

if not "all_submons" in session:
    session["all_submons"] = [_dict]
else:
    session["all_submons"] = session["all_submons"] + [_dict]

session.modified = True

all_submons.setdefault("sub_mons", []).append(_dict)

print(f"Session after: {session}")
print(f"all_submons after: {all_submons}\n")

您可以检查输出:

Session before: <SecureCookieSession {'_fresh': True, '_id': 'e253a950...', 'all_submons': [], 'user_id': '1'}>

all_submons before: {}

Session after: <SecureCookieSession {'_fresh': True, '_id': 'e253a...', 'all_submons': [{'sid': 'e253a95...', 'licycle': <itertools.cycle object at 0x7fc989237280>, 'nextelem': ('1a4add0f275c7275.jpg',), 'licycle2': None, 'nextelem2': None, 'mon_id': 1, 'sch_id': 0}], 'user_id': '1'}>

all_submons after: {'sub_mons': [{'sid': 'e253a...', 'licycle': <itertools.cycle object at 0x7fd6f1a17b80>, 'nextelem': ('1a4add0f275c7275.jpg',), 'licycle2': None, 'nextelem2': None, 'mon_id': 1, 'sch_id': 0}]}

我不确定会话可能不接受"那种类型的变量-< class'itertools.cycle'>

I'm not sure about session "probably doesn't accepts" that type of variable - <class 'itertools.cycle'>

但是我用其他变量创建了其他词典,但没有itertools.cycle类型,并且可以正常工作.

But I created other dictionary with others variables, without type of itertools.cycle and it worked.

这篇关于Flask-TypeError:类型为cycle的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆