Weather App using Flask – Check Temperature & Humidity by City Name using OpenWeatherMap API (Python Project)

Flask Weather App using Python | Web Project

🌤️ Weather Web App using Python Flask

This simple project helps you build a web app using Python Flask and the OpenWeatherMap API. The user enters a city name, and the app returns temperature and humidity.

📁 Project Structure:

weatherapp/
├── weather.py
├── static/
│   └── style.css
└── templates/
    └── index.html
  

📦 Required Python Modules


pip install flask
pip install requests
  

🐍 weather.py (Python Flask Code)


from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    temperature = None
    humidity = None  
    city = None
    error_message = None  

    if request.method == "POST":
        city = request.form["city"]
        API_KEY = "your_api_key_here"
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

        try:
            response = requests.get(url, timeout=8)
            if response.status_code == 404:
                error_message = "City not found. Please enter a valid city name."
            else:
                response.raise_for_status()
                data = response.json()
                if "main" in data:
                    temperature = data["main"]["temp"]
                    humidity = data["main"]["humidity"]  
                else:
                    error_message = "Weather data not found for the city."
        except requests.exceptions.Timeout:
            error_message = "Request timed out. Please try again later."
        except requests.exceptions.ConnectionError:
            error_message = "Network issue. Please check your internet connection."
        except requests.exceptions.RequestException as e:
            error_message = f"Error: {str(e)}"

    return render_template("index.html", temperature=temperature, humidity=humidity, city=city, error_message=error_message)

if __name__ == "__main__":
    app.run(debug=True)
  

📄 index.html (inside templates folder)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>Weather App</title>
</head>
<body>

    <h1 class="Heading">⛅Weather App</h1>

    <div class="Container">
        <form method="POST">
            <input class="InputField" type="text" name="city" placeholder="Enter city name..." required>
            <button class="ButtonField" type="submit">Get Weather</button>
        </form>
    </div>

    {% if error_message %}
        <p class="ErrorMessage">{{ error_message }}</p>
    {% endif %}

    {% if temperature is not none and humidity is not none %}
        <div class="ResultContainer">
            <h2>Weather in 🌆 {{ city }}</h2>
            <p>🌡️ Temperature: {{ temperature }}°C</p>
            <p>💧 Humidity: {{ humidity }}%</p>
        </div>
    {% endif %}

</body>
</html>
  

🎨 style.css (inside static folder)


body {
    background-color: rgb(51, 98, 199);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 100px;
}

.Container {
    width: 30%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.Heading {
    margin-bottom: 12px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    color: white;
}

.InputField {
    width: 98%;
    height: 40px;
    border: none;
    border-radius: 15px;
    font-size: 18px;
    font-weight: bold;
    padding-left: 10px;
    margin-bottom: 12px;
}

.ButtonField {
    width: 100%;
    height: 40px;
    border: none;
    border-radius: 15px;
    background-color: orange;
    color: white;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 12px;
}

h2, p {
    color: white;
    font-size: 20px;
    font-family: 'Courier New', Courier, monospace;
    font-weight: bold;
}

.ErrorMessage {
    color: red;
    font-weight: bold;
    margin-top: 10px;
}
  

✅ Summary

  • 💻 Built using Flask (Python web framework)
  • 📡 Calls OpenWeatherMap API to get weather data
  • 🎨 Styled using external CSS file
  • 📁 Uses proper project structure (static & templates)

👉 Follow our blog and YouTube for more simple & useful Python projects!

Post a Comment

Previous Post Next Post