Flask API Typeerror: Object of Type 'Response' Is Not Json Serializable

Flask API throws TypeError: Object of type is not JSON serializable

The error is direct, that you have values that are not JSON ready in your response.

You have an item in your dict , 'outlets':contact.outlets,, which is ideally a list of Outlet objects as per your model definition. You need to tell flask-jsonify, how to make that object a JSON

In a normal json.dumps operation, you can do this by passing a custom encoder or default method. You can do this, by setting the encoder option in flask.

First, you create a custom model encoder for JSON. An example could be like below

from flask import json
class ModelEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
if hasattr(o, 'to_json'):
return o.to_json()
else:
return super(ModelEncoder, self).default(o)

And now, ask flask to use this encoder for converting models to JSON. For this you can set the flask app configuration.

app.json_encoder = ModelEncoder

If you have a to_json method in your model, it will call that for serializing those. Other wise it follows the default. Yes, this is a simple implementation, you can improvise with type checks or variations.

TypeError: Object of type set is not JSON serializable This is the error I'm getting

you need to add the resource save_data,

api.add_resource(save_data, '/save_data')

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

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.

Flask unable to send image back in json response

This is because your get_user_image function returns a stream of bytes and not a string, so you have to cast the bytes read into a string: get_user_image(usr_rec["recordid"]).decode("utf-8"). The same happens for the object of type Decimal.

The jsonify function only serializes objects of type string, as you can also see here and here



Related Topics



Leave a reply



Submit