繁体   English   中英

Flask object X 型不可序列化 JSON

[英]Flask object type X is not JSON serializable

我正在使用 Flask、SQLAlchemy、棉花糖等......

这个 Flask 方法可以很好地将对象保存到数据库中,但是它在 return 语句上出错。

这是父 class:

class Weather(db.Model):
    """Weather definition for SQLAlchemy"""
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    coordinates = db.relationship("Coordinate", backref="Weather", uselist=False)  # coordinates (decmial)
    hygrometer = db.Column(db.Float, nullable=False)  # hygrometer (0.0 -100)
    thermometer = db.Column(db.Float, nullable=False)  # thermometer (-200 - 200)
    udometer = db.Column(db.Integer, nullable=False)  # udometer (0-3000)
    anemometer = db.Column(db.Integer, nullable=False)  # anemometer (0-500)
    vane = db.Column(db.Integer, nullable=False)  # vane (0-360)
    #date = db.Column(db.String, nullable=False) # this is the old manual
    date = db.Column(db.DateTime(timezone=True), default=func.now()) # this gets auto generated

    def __repr__(self):
        return '<Weather %r>' % self.id

class WeatherSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        fields = ("id", "coordinates", "hygrometer", "thermometer", "udometer", "anemometer", "vane", "date")


weather_schema = WeatherSchema()
weathers_schema = WeatherSchema(many=True)

这是子 class:

class Coordinate(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    longitude = db.Column(db.Float, nullable=False)  # coordinates (decmial)
    latitude = db.Column(db.Float, nullable=False)  # coordinates (decmial)
    Weather_id = db.Column(db.Integer, db.ForeignKey("weather.id"), nullable=False)

    def __repr__(self):
        return '<Coordinate %r>' % self.id


class CoordinateSchema(ma.SQLAlchemyAutoSchema):
    # definition used by serialization library based on user
    class Meta:
        fields = ("id", "longitude", "latitude", "weather_id")


coordinate_schema = CoordinateSchema()
coordinates_schema = CoordinateSchema(many=True)

这是方法:

@app.post("/weathers/add")  # ADD
def weather_add_json():
    request_data = request.get_json()
    print(request_data)
    new_coordinate = Coordinate(
        longitude=request_data['longitude'],
        latitude=request_data['latitude']
    )
    new_weather = Weather(
        coordinates=new_coordinate,
        hygrometer=request_data['hygrometer'],
        thermometer=request_data['thermometer'],
        udometer=request_data['udometer'],
        anemometer=request_data['anemometer'],
        vane=request_data['vane']
    )
    print(new_weather)
    try:
        db.session.add(new_weather)
        db.session.commit()
        print("Record added to DB")
        print(json.dumps(request_data, indent=4))
    except Exception as e:
        print(e)
    return weather_schema.jsonify(new_weather)

这是 HTTP 请求:

POST http://127.0.0.1:5000/weathers/add
Content-Type: application/json

{
  "longitude": "45.5",
  "latitude": "92.6",
  "hygrometer": "1.5",
  "thermometer": "22.5",
  "udometer": "2200",
  "anemometer": "250",
  "vane": "92"
}

这是错误:

 line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Coordinate is not JSON serializable
127.0.0.1 - - [27/Dec/2021 18:51:24] "POST /weathers/add HTTP/1.1" 500 -

下面是每个表的内容:

天气:

4,1.5,22.5,2200,250,92,2021-12-27 18:22:16
5,1.5,22.5,2200,250,92,2021-12-27 18:35:31
6,1.5,22.5,2200,250,92,2021-12-27 18:36:43
7,1.5,22.5,2200,250,92,2021-12-27 18:38:28

协调:

4,45.5,92.6,4
5,45.5,92.6,5
6,45.5,92.6,6
7,45.5,92.6,7

这种父子结构是按照指南完成的,但是我觉得它好像是错误的,它失败了 3NF 并且实际上并没有参考天气表中的坐标。

应该是天气 -> WeatherCoordinate -> 坐标吗? 我不确定我将如何构建它,也许是一个全新的 object 或者它可以自动搭建吗?

weather_schema.jsonify(new_weather)

我不明白。 这应该引发AttributeError因为模式没有jsonify方法。

无论如何,您需要使用模式转储内容。

这应该有效。

weather_schema.dumps(new_weather)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM