Flask - TypeError: Object of type cycle is not JSON serializable

161 views Asked by At

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

Like this, it works:

@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 ''

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 I remove that stretch:

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

      session.modified = True

It works again. Client receives json response.

0

There are 0 answers