簡體   English   中英

"帶有 Marshmallow 的 Flask Alchemy 返回空 JSON"

[英]Flask Alchemy with Marshmallow returns empty JSON

我正在嘗試使用 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)

我的模型:

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)

我的架構:

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

這是從控制台看到的結果:

 * 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 -

有什么我想念的嗎? 任何人都可以幫忙嗎?

在 CustomerSchema 中,您應該傳遞參數為 many=True,正如您期望的列表,例如:customers_schema = CustomerSchema(many=True)

我想在上面的答案中添加一些內容。

在 Marshmallow 3.x 中,參數strict已被刪除,因為架構始終是嚴格的。

作為結果的空 JSON 對象可能是由不同的情況引起的,例如我曾經在架構中將“=”誤認為“:”,這導致了[ Unknown field. ] [ Unknown field. ]在轉儲上,結果是一個空的 JSON 對象。

為了在 Marshmallow 3.x 中進行調試,您可以使用Schema.validate返回驗證錯誤字典:

  customers_schema = CustomerSchema()

  print(customers_schema.validate(customers))

我希望這可以在未來幫助一些人

您可能在序列化過程中遇到了一些錯誤,而您只是忽略了它。 嘗試使用strict=True實例化您的架構以查看存在哪些錯誤:

customers_schema = CustomerSchema(strict=True)

另外,請確保如果您嘗試驗證來自.query()的數據庫響應不是 orm 映射對象,而是轉換為字典,如下所述: 如何將 SQLAlchemy 行對象轉換為 Python 字典? row2dict代碼示例中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM