-1

I am using Flask, SQLAlchemy, Marshmallow etc....

This Flask method saves the objects to the database fine, however it errors on the return statement.

This is the parent 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)

This is the child 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)

This is the method:

@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)

This is the HTTP request:

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"
}

This is the error:

 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 -

The below is the content of each table:

Weather:

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

Coordinate:

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

This structure for parent-child was done following a guide, however i feel as though it is wrong, it fails 3NF and doesn't actually reference coordinates from the weather table.

Should it be a Weather -> WeatherCoordinate -> Coordinate ? I'm not sure how I would structure this though, maybe an entirely new object or can this be scaffolded automatically?

ABpositive
  • 291
  • 1
  • 18

1 Answers1

0
weather_schema.jsonify(new_weather)

I don't get it. This should raise an AttributeError as schemas don't have a jsonify method.

Anyway, you need to dump the content with the schema.

This should work.

weather_schema.dumps(new_weather)
Jérôme
  • 13,328
  • 7
  • 56
  • 106