-2

I have a model Service to save data from ping probes, so i ping at the IP address, i must enter the result value in a list "history" of 30 values, delete the oldest value in that list and calculate the average to save the list and the average in the database.

class Service(peewee.Model):
    identifier = peewee.CharField(max_length=30, primary_key=True)
    ip = peewee.CharField(max_length=15)
    latency = peewee.CharField(max_length=10)
    history = peewee.CharField(max_length=1000)
    device = peewee.ForeignKeyField(Core, on_delete='CASCADE')

I could create the functions to calculate and average, do the round robin and then save the results to the database, or I could try to serialize the model in a dataclass and implement the necessary functions. Which would be the best option? what would be the best practice?.

To keep in mind, I must iterate this procedure in several services.

ehidoz
  • 21
  • 5

1 Answers1

0

If it were me, I would store one row per ping per IP, so your rows would look like:

123 | 1.1.1.2 | 2022-08-15T12:34:56 | 30ms
124 | 1.1.1.3 | 2022-08-15T12:34:56 | 18ms
... (other rows here) ...
151 | 1.1.1.2 | 2022-08-15T12:35:25 | 38ms
152 | 1.1.1.3 | 2022-08-15T12:35:25 | 21ms
... etc

Each time you add a new row, you can use a window function or similar to trim extra rows. To calculate average latencies, e.g., you might

select avg(latency) from my_table where ip = '1.1.1.2';
coleifer
  • 24,887
  • 6
  • 60
  • 75
  • thanks for the reply. That is a good idea, however, the average is a state of a service, my specific doubt is if when using peewee as my ORM I should calculate the value and modify the model directly or calculate the value in a dataclass – ehidoz Aug 16 '22 at 02:05