You can download this code by clicking the button below.
This code is now available for download.
This function accepts a MongoDB client and a city name, then retrieves the weather records for that city from the MongoDB database and generates a weather report containing the average temperature, highest temperature, and lowest temperature.
Technology Stack : Beanie, PydanticObjectId, AsyncIOMotorClient, Numpy, Pandas
Code Type : Function
Code Difficulty : Intermediate
import numpy as np
import pandas as pd
from beanie import Document, PydanticObjectId
from motor.motor_asyncio import AsyncIOMotorClient
class WeatherRecord(Document):
date: str
temperature: float
description: str
async def generate_weather_report(client: AsyncIOMotorClient, city: str):
db = client.weather_data
records = await db.WeatherRecord.find_one({"city": city})
if records:
daily_temps = [record.temperature for record in records['records']]
avg_temp = np.mean(daily_temps)
max_temp = np.max(daily_temps)
min_temp = np.min(daily_temps)
report = f"Average temperature for {city} was {avg_temp:.2f} with a high of {max_temp:.2f} and a low of {min_temp:.2f}."
return report
else:
return f"No weather records found for {city}."