From 108fc02b980f102482ec39597ff24e9f6ad8bdf1 Mon Sep 17 00:00:00 2001 From: Mark Rouzm <83913652+Ludusm11@users.noreply.github.com> Date: Thu, 3 Oct 2024 10:43:09 +0200 Subject: [PATCH] Enhancements for Error Handling and Input Validation - Added error handling for failed API requests (e.g., invalid city or API issues). - Improved input validation by trimming spaces and handling empty city input. - Used .get() to prevent KeyError when accessing potentially missing fields in the API response. - Displayed a custom error page when a city is not found in the API response. - Ensured the application does not crash when API data is incomplete or unavailable. --- server.py | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/server.py b/server.py index 47d93d1..024cd44 100644 --- a/server.py +++ b/server.py @@ -1,43 +1,36 @@ from flask import Flask, render_template, request from weather import get_current_weather -from waitress import serve # production server - +from waitress import serve app = Flask(__name__) - @app.route("/") @app.route("/index") def index(): - # return "Hello, World!" return render_template("index.html") - @app.route("/weather") def weather(): - city = request.args.get("city") + city = request.args.get("city", "").strip() - # check for empty strings and string with only spaces - if not bool(city.strip()): + if not city: city = "Locquirec" - # Retrieve weather data from the API - weather_data = get_current_weather(city) - - # City is not found by the API - if not weather_data["cod"] == 200: - return render_template("city-not-found.html") - - return render_template( - "weather.html", - title=weather_data["name"], - status=weather_data["weather"][0]["description"].capitalize(), - temp=f"{weather_data['main']['temp']:.1f}", - feels_like=f"{weather_data['main']['feels_like']:.1f}", - ) - + try: + weather_data = get_current_weather(city) + if "cod" not in weather_data or weather_data["cod"] != 200: + return render_template("city-not-found.html", city=city) + + return render_template( + "weather.html", + title=weather_data.get("name", "Unknown City"), + status=weather_data.get("weather", [{}])[0].get("description", "No data").capitalize(), + temp=f"{weather_data['main'].get('temp', 'N/A'):.1f}", + feels_like=f"{weather_data['main'].get('feels_like', 'N/A'):.1f}", + ) + except Exception as e: + return f"Error: {str(e)}", 500 if __name__ == "__main__": - # app.run(host="0.0.0.0", port=8000) # development server print("\n ** Starting the server ** \n") - serve(app, host="0.0.0.0", port=8000) # using waitress for production server + serve(app, host="0.0.0.0", port=8000)