Jer*_*emy 2 python json flask flask-sqlalchemy flask-restful
我试图使用Flask Alchemy和Flask Marshmallow从数据库查询后返回json数据
但是,我的代码总是以某种方式返回空的JSON数据。
这是我的代码:
我的看法 :
@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)
Run Code Online (Sandbox Code Playgroud)
我的模特:
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)
Run Code Online (Sandbox Code Playgroud)
我的架构:
class CustomerSchema(ma.ModelSchema):
class Meta:
model = Customer
Run Code Online (Sandbox Code Playgroud)
这是从控制台看到的结果:
* 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 -
Run Code Online (Sandbox Code Playgroud)
我有什么想念的吗?有人可以帮忙吗?
我想在上面的答案中添加一些内容。
在 Marshmallow 3.x 中,该参数strict
已被删除,因为模式始终是严格的。
结果为空 JSON 对象可能是由不同的情况引起的,例如,我曾经在模式中将“=”与“:”错误,这导致转储[ Unknown field. ]
和空 JSON 对象作为结果。
为了在 Marshmallow 3.x 中进行调试,您可以使用Schema.validate
它返回验证错误的字典:
customers_schema = CustomerSchema()
print(customers_schema.validate(customers))
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助一些人在未来
您可能在序列化过程中遇到了一些错误,但您只是忽略它。尝试实例化您的架构以strict=True
查看存在哪些错误:
customers_schema = CustomerSchema(strict=True)