0

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.

rjunior8
  • 23
  • 6
  • Hey! Unfortunately I cannot reproduce the behaviour you describe with the given code snippets. Could you provide a [minimum, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) for the problem? – oschlueter Sep 27 '20 at 16:52
  • @oschlueter I did sovled. I published here: https://stackoverflow.com/questions/64081846/flask-typeerror-object-of-type-cycle-is-not-json-serializable I accidentally migrated (duplicated) the question. That's why I have this question in two places. – rjunior8 Sep 28 '20 at 19:19

0 Answers0