[server]: Only use Decimal values in update_average_punctuality
This commit is contained in:
@ -1,10 +1,13 @@
|
||||
import json
|
||||
import boto3
|
||||
import requests
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
dynamodb = boto3.resource("dynamodb")
|
||||
table = dynamodb.Table("punctuality_by_objectID")
|
||||
API_URL = "https://281bc6mcm5.execute-api.us-east-1.amazonaws.com/transient_data?objectType=IrishRailTrain"
|
||||
API_URL = "https://your-api-endpoint.com" # Replace with your actual API URL
|
||||
|
||||
|
||||
def fetch_train_data():
|
||||
response = requests.get(API_URL)
|
||||
@ -16,21 +19,25 @@ def fetch_train_data():
|
||||
|
||||
|
||||
def update_punctuality(objectID, new_punctuality):
|
||||
new_punctuality = Decimal(str(new_punctuality)) # Ensure Decimal type for DynamoDB
|
||||
response = table.get_item(Key={"objectID": objectID})
|
||||
if "Item" in response:
|
||||
item = response["Item"]
|
||||
old_avg = float(item["average_punctuality"])
|
||||
old_avg = Decimal(str(item["average_punctuality"]))
|
||||
count = int(item["count"])
|
||||
|
||||
# Calculate new average
|
||||
new_avg = ((old_avg * count) + new_punctuality) / (count + 1)
|
||||
count += 1
|
||||
|
||||
# Update the DynamoDB table
|
||||
table.update_item(
|
||||
Key={"objectID": objectID},
|
||||
UpdateExpression="SET average_punctuality = :avg, count = :cnt",
|
||||
ExpressionAttributeValues={":avg": new_avg, ":cnt": count}
|
||||
)
|
||||
else:
|
||||
# Insert new train punctuality record
|
||||
table.put_item(
|
||||
Item={"objectID": objectID, "average_punctuality": new_punctuality, "count": 1}
|
||||
)
|
||||
|
Reference in New Issue
Block a user