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
  • 2
    Does this answer your question? [Flask - TypeError: Object of type cycle is not JSON serializable](https://stackoverflow.com/questions/64081130/flask-typeerror-object-of-type-cycle-is-not-json-serializable) – Robert Longson Sep 26 '20 at 20:43

1 Answers1

0

I figured out the trouble.

Check out the following function:

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

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.

The point is:

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")

You can check the output:

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}]}

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

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

rjunior8
  • 23
  • 6