Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Alchemy with Marshmallow returns empty JSON

I am trying to return a json data after query from my database using Flask Alchemy, and Flask Marshmallow

However, my code somehow always returns empty JSON data.

Here's my code :

My View :

@app.route('/customer/', methods=['GET'])
def get_customer():
  customers = models.Customer.query.all()
  #c = models.Customer.query.get(1) # Get Customer with an ID of 1

  customers_schema = CustomerSchema()

  print customers_schema.dump(customers).data
  payload = customers_schema.dump(customers).data
  resp = Response(response=payload, status=200, mimetype="application/json")
  return(resp)

My Models :

class Customer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    address = db.relationship('Address', backref='customer', lazy='dynamic')

    def __repr__(self):
        return '<Customer %r>' % (self.nickname)

My Schema :

class CustomerSchema(ma.ModelSchema):
    class Meta:
        model = Customer

This is the result as seen from the console :

 * Debugger is active!
 * Debugger pin code: 817-774-044
{}
127.0.0.1 - - [12/Nov/2016 09:37:59] "GET /customer/ HTTP/1.1" 200 -
{}
127.0.0.1 - - [12/Nov/2016 09:41:27] "GET /customer/ HTTP/1.1" 200 -

Is there anything that i miss ? Can anyone help ?

like image 375
Jeremy Avatar asked Nov 12 '16 02:11

Jeremy


3 Answers

In CustomerSchema you should pass the parameter as many=True, as you expect a list, such as: customers_schema = CustomerSchema(many=True)

like image 81
user7801624 Avatar answered Oct 23 '22 05:10

user7801624


I'd like to add something to the answers above.

In Marshmallow 3.x, the parameter strict has been removed as schemas are always strict.

An empty JSON object as result may be caused by different cases, for instance I have once mistaken "=" with ":" in the schema which results in a [ Unknown field. ] on dumps and an empty JSON Object as result.

In order to debug in Marshmallow 3.x you may use Schema.validate which returns a dictionary of validation errors :

  customers_schema = CustomerSchema()

  print(customers_schema.validate(customers))

I hope this may help some people in the future

like image 28
Pierre Welmant Avatar answered Oct 23 '22 04:10

Pierre Welmant


You are probably hitting some error during serialization and you just ignore it. Try instantiating you schema with strict=True to see what errors are there:

customers_schema = CustomerSchema(strict=True)

like image 25
Maxim Kulkin Avatar answered Oct 23 '22 06:10

Maxim Kulkin