0

The POST request is successful and the data is posted to the database, but I always get this error.

TypeError: Object of type User is not JSON serializable

Tried making it a __dict__ but that just then created different errors. How to stop this error?

In my schema.py file

from flask import Flask
from app import db, ma
import os

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(30), unique=False)
    last_name = db.Column(db.String(30), unique=False)
    email = db.Column(db.String(120), unique=True)
    specialization = db.Column(db.String(50), unique=False)
    user_type = db.Column(db.String(20), unique=False)

    def __init__(self, first_name, last_name, email, specialization, user_type):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email
        self.specialization = specialization
        self.user_type = user_type


class UserSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ('first_name', 'last_name', 'email', 'specialization', 'user_type')

user_schema = UserSchema()
users_schema = UserSchema(many=True)

In my app.py file

from flask import Flask, render_template, request, jsonify
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

@APP.route("/patient", methods=["POST"])
def add_appointment():
    first_name = request.json['first_name']
    last_name = request.json['last_name']
    email = request.json['email']
    specialization = request.json['specialization']
    user_type = request.json['user_type']

    new_user = schema.User(first_name, last_name, email, specialization, user_type)

    schema.db.session.add(new_user)
    schema.db.session.commit()

    return jsonify(new_user)

I'm running my flask app from virtual environment on a raspberry pi and connecting to a Google cloud mysql database (if that makes any differences).

crazyPen
  • 823
  • 3
  • 10
  • 19
  • Possible duplicate of [How to make a class JSON serializable](https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable) – glibdud Sep 13 '18 at 13:52
  • Or possibly [jsonify a SQLAlchemy result set in Flask](https://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask)? – glibdud Sep 13 '18 at 13:55

1 Answers1

1

It seems that the marshmallow schema is not being used. This might work,

schema.db.session.add(new_user)
schema.db.session.commit()

result, errors = schema.user_schema.dump(new_user)

return jsonify(result)
J.J. Hakala
  • 6,136
  • 6
  • 27
  • 61