'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 ?
Solution 1:[1]
In CustomerSchema you should pass the parameter as many=True, as you expect a list, such as: customers_schema = CustomerSchema(many=True)
Solution 2:[2]
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
Solution 3:[3]
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)
Solution 4:[4]
Also, make sure that if you try to validate a database response from .query() is not an orm-mapped object and is rather converted to a dictionary, as described here: How to convert SQLAlchemy row object to a Python dict?
in the row2dict code sample.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user7801624 |
| Solution 2 | Pierre Welmant |
| Solution 3 | Maxim Kulkin |
| Solution 4 | Cactus |
