weather_api/main.py
Argiris Deligiannidis 46a5b5c039 Update code base
2024-04-07 13:01:31 +03:00

107 lines
2.8 KiB
Python

from fastapi import FastAPI, status, HTTPException
from models import Location
from db_connector import database,engine
import utils
db_rebuild = True
database.metadata.drop_all(engine)
if db_rebuild:
utils.initialize_database()
app = FastAPI()
def error_400_handler(return_data):
"""
A function that handles errors with status code 400. Takes return_data as input.
Checks if the key 'error' exists in the data dictionary. If it does, it raises an HTTPException
with status code 400 and the value of the 'error' key as the detail.
"""
if 'error' in return_data.keys():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={'error': return_data['error']}
)
@app.get("/")
async def index_response():
return {"Status": "OK"}
@app.get("/locations")
async def get_location_weather(places: str):
"""
A function to retrieve weather data for specified locations.
Parameters:
places (str): A string containing location identifiers separated by commas.
Returns:
dict: A dictionary containing weather data for the specified locations.
"""
#NOTE: Add option for fetching weather data for all locations, (debugging purposes)
if places != 'all':
places = [int(x) for x in list(places.split(","))]
result = utils.retrieve_weather_data(places)
error_400_handler(result)
return result
@app.get("/locations/{id}")
async def get_weather_by_id(id: int):
"""
A function that retrieves weather data for a location by its ID.
Parameters:
- id: an integer representing the ID of the location
Returns:
- The weather data for the specified location
"""
result = utils.retrieve_weather_data([id])
error_400_handler(result)
return result
@app.post("/locations", status_code=status.HTTP_201_CREATED)
async def add_location(
name: str = None,
longitude: float = None,
latitude: float = None,
):
"""
Add a new location to the database.
Parameters:
- name (str): The name of the location.
- longitude (float): The longitude coordinate of the location.
- latitude (float): The latitude coordinate of the location.
"""
if len(name.encode('utf-8')) > 200:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail={'name': 'Name cannot be longer than 200 characters'}
)
else:
utils.add_location(Location(name=name,longitude=longitude,latitude=latitude))
@app.delete("/locations/{id}")
async def delete_location(id: int):
"""
Delete a location by its ID.
Parameters:
id (int): The ID of the location to be deleted.
Returns:
None
"""
utils.delete_location(id)