【问题标题】:Flask object type X is not JSON serializableFlask 对象类型 X 不是 JSON 可序列化的
【发布时间】:2022-01-26 15:31:48
【问题描述】:

我正在使用 Flask、SQLAlchemy、Marshmallow 等......

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

这是父类:

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 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 并且实际上并没有参考天气表中的坐标。

应该是 Weather -> WeatherCoordinate -> Coordinate 吗? 不过,我不确定我将如何构建它,可能是一个全新的对象,还是可以自动搭建?

【问题讨论】:

    标签: python sqlite flask sqlalchemy marshmallow


    【解决方案1】:
    weather_schema.jsonify(new_weather)
    

    我不明白。这应该引发AttributeError,因为架构没有jsonify 方法。

    无论如何,您需要将内容与架构一起转储。

    这应该可行。

    weather_schema.dumps(new_weather)
    

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2020-09-05
      • 2019-03-05
      • 2019-07-12
      • 1970-01-01
      • 2017-11-09
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多