Weather in the world

Description:

This application is a simple Flask-based web app that allows users to search for weather information for a specific city by inputting the city name, state, and country. The app integrates with an external weather API to retrieve real-time weather data and stores this information in a local SQLite database.

Features

Weather Search: Users can input a city name, state, and country, and the app will fetch the current weather data (such as temperature) for the given location using the weather API.Data Storage: The weather data fetched from the API is stored in an SQLite database. Each query inserts the city name and its temperature into the weather table.Weather History: After each weather query, all previously searched cities and their weather data are displayed on the homepageAn SQLite database (weather.db) is used to store the city name and temperature. The schema for the database is defined in the app

Files

app.py: The main Flask application script.weather.py: A module responsible for fetching weather data from an API.index.html: The front-end template for rendering the weather data and search form.weather.db: The SQLite database where the weather data is stored.

weather.py

libraries:

import requests: Imports the requests library, which is used to make HTTP requests to external APIs (in this case, OpenWeatherMap API).from dotenv import load_dotenv: Imports the load_dotenv function from the dotenv module, which is used to load environment variables (like the API key) from a .env file.from dataclasses import dataclass: Imports the dataclass decorator from Python's dataclasses module. This is used to easily create a class for storing structured data (e.g., weather info).import os: Imports the built-in os module, which allows interaction with the operating system, such as accessing environment variables.

code

load_dotenv(): Loads the environment variables from a .env file into the Python environment, making them available via os.getenv(). This is where the API key will be stored securely.api_key = os.getenv('API_KEY'): Retrieves the value of the API_KEY environment variable (from the .env file) and stores it in the api_key variable. If API_KEY is not found, None is returned.@dataclass: A decorator that automatically generates special methods (like init, repr, etc.) for the class WeatherData.class WeatherData: Defines a class WeatherData to store weather information.main: str, description: str, icon: str, tempeture: int: These are the attributes of the *WeatherData class, which will store the main weather type (e.g., "Clouds"), description (e.g., "scattered clouds"), icon (for displaying weather images), and temperature (as an integer).Retrieves the value of the API_KEY environment variable (from the .env file) and stores it in the api_key variable. If API_KEY is not found, None is returned.def get_lat_lon(city_name, state_code, country_code, API_key):: This function takes the city name, state, country, and the API key as inputs and retrieves the latitude and longitude of the city using OpenWeatherMap’s Geocoding API.def get_current_weather(lat, lon, API_key):: This function takes the latitude, longitude, and API key as input and retrieves the current weather information for that location from OpenWeatherMap's Weather API.requests.get(...).json(): Sends a GET request to OpenWeatherMap’s Weather API using the latitude, longitude, and API key. The units=metric parameter is added to ensure that the temperature is returned in Celsius. The .json() method converts the response into a Python dictionary.def main(city_name, statename, country_name):: The main function that combines the previous two functions: Calls get_lat_lon() to retrieve the latitude and longitude. Calls get_current_weather() to retrieve the weather information based on the coordinates. Returns the final weather data.def main(city_name, statename, country_name)::The main function that combines the previous two functions: Calls get_lat_lon() to retrieve the latitude and longitude. Calls get_current_weather() to retrieve the weather information based on the coordinates. Returns the final weather data.

weather db:

the waether data base has only a table and is made as follows: id (Primary Key, Autoincrement) city_name (Text) temperature (Real) The database table is recreated each time the app starts by dropping any existing table and creating a new one. this is made in app.py

app.py

libraries:

from cs50 import SQL: Imports the SQL class from the cs50 library, which is used to interact with a SQLite database.from flask import Flask, render_template, request: Imports the essential Flask components:from weather import main as get_weather: Imports the main function from the weather.py file and renames it as get_weather for use in this script. This function is used to fetch the weather data from the OpenWeather API.

code

app = Flask(name): Creates an instance of the Flask class, which represents the Flask web application. The name variable is passed to tell Flask the name of the module, which helps it locate resources like templates and static files.db = SQL("sqlite:///weather.db"): Initializes the connection to the SQLite database named weather.db using the SQL class. This will be used to execute SQL queries to interact with the database.db.execute("DROP TABLE IF EXISTS weather"): Executes an SQL query that drops (deletes) the weather table from the database if it already exists. This ensures a clean slate when creating the table later.db.execute(""" CREATE TABLE ... """): Executes an SQL query that creates a new table named weather@app.route("/", methods=['GET', 'POST']): Defines the route for the root URL /, which is the home page. This function supports both GET (default) and POST HTTP methods.data = None: Initializes a variable data to None. This variable will store the weather data retrieved from the API and will be passed to the HTML template later. Initializing it ensures that the template can render properly, even if no data is available.search = None: Initializes a search variable to None. This will be used to store data retrieved from the database and passed to the HTML templatedata = get_weather(city, state, country): Calls the get_weather function (imported from the weather.py script) with the city, state, and country as arguments. This function fetches the weather information from the weather API and stores it in the data variable.db.execute(...): Executes an SQL INSERT query to insert the city name and temperature into the weather table. The data.tempeture value comes from the API response.search = db.execute("SELECT * FROM weather"): Executes an SQL SELECT query to retrieve all rows from the weather table and stores the result in the search variable.return render_template('index.html', data=data, search=search): Renders the index.html template, passing the data (weather information) and search (results from the weather database) to the template. This allows the HTML page to display the weather data and search results.** if name == 'main':** This ensures that the Flask app will only run if the script is executed directly (i.e., not imported as a module in another Python script).app.run(debug=True): Starts the Flask development server with debug=True, which means that the app will auto-reload when changes are made to the code, and detailed error messages will be shown if something goes wrong. This is useful for development, but not recommended in production

index.html

This HTML page displays weather information using Bootstrap for styling. It has a form that allows users to input a city, state, and country. Upon submission, the weather data is displayed using Jinja templating, which shows the weather description, icon, and temperature. The table below shows recent weather searches retrieved from a database. Bootstrap is used for layout and responsiveness, with external CSS and JavaScript files linked via CDN. The form submits data using the POST method to the server's root URL (/). The page dynamically updates content using Jinja templating