general_posts/python-weather-api/api/services.py

48 lines
1.6 KiB
Python

from datetime import datetime
from api.error import Error
from model.historic import HistoricWeather
from model.current import CurrentWeather
from model.forecast import ForecastWeather
class BaseService:
def __init__(self, database=None):
self.database = database
class HistoricWeatherService(BaseService):
DATE_FORMAT = "%Y-%m-%d"
def get_historic_weather(self, location, date=None):
query = self.database.session.query(HistoricWeather).filter_by(city=location)
if date:
try:
parsed_date = datetime.strptime(date, self.DATE_FORMAT)
query = query.filter_by(date=parsed_date)
except ValueError:
raise Error("Date must be YYYY-MM-DD format", 400)
results = query.all()
if not results:
raise Error("Resource Not Found", 404)
return [result.to_dict() for result in results]
class CurrentWeatherService(BaseService):
def get_current_weather(self, location):
query = self.database.session.query(CurrentWeather).filter_by(city=location)
results = query.all()
if not results:
raise Error("Resource Not Found", 404)
return [result.to_dict() for result in results]
class ForecastWeatherService(BaseService):
def get_forecast_weather(self, location):
query = self.database.session.query(ForecastWeather).filter_by(city=location)
results = query.all()
if not results:
raise Error("Resource Not Found", 404)
return [result.to_dict() for result in results]