Python 3.x raise TypeError(repr(o)&“x2B”不可JSON序列化”
我正试图根据这个项目对一些代码进行建模 这是我用python编写的第一个RESTAPI。这是代码Python 3.x raise TypeError(repr(o)&“x2B”不可JSON序列化”,python-3.x,rest,Python 3.x,Rest,我正试图根据这个项目对一些代码进行建模 这是我用python编写的第一个RESTAPI。这是代码 from marshmallow import Schema, fields class Product(): def __init__(self, ident, name, description, category): self.ident = ident self.name = name self.description = description
from marshmallow import Schema, fields
class Product():
def __init__(self, ident, name, description, category):
self.ident = ident
self.name = name
self.description = description
self.category = category
def __repr__(self):
return '<Expense(name={self.description!r})>'.format(self=self)
class ProductSchema(Schema):
ident = fields.Str()
name = fields.Str()
category = fields.Str()
description = fields.Str()
但是,当我尝试对/products执行http GET请求时,我在描述中发现了错误。您有两个问题:
产品
类型为列表,而jsonify不是结果列表,因为它不安全Product()
对象是类,您需要返回dictimport json
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return json.dumps([p.__dict__ for p in prodacts])
或
你想做什么获取或发布?我想做的是获取这些作品,但看起来它没有使用棉花糖来序列化
import json
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return json.dumps([p.__dict__ for p in prodacts])
from flask import Response
import json
@app.route("/products")
def get_products():
schema = ProductSchema(many=True)
return Response(json.dumps([p.__dict__ for p in prodacts]), mimetype='application/json')