How to Build a Flask Weather App Using Python

How to Build a Flask Weather App Using Python

Introduction

Install modules

pip3 install Flask 
pip3 install requests

Create files

Now after installing the modules let’s now create a folder called flask-weather inside it create a folder called templates and create a file called index.html.

Import modules

Now inside the flask-weather folder create a file called app.py and import the following modules as shown.

from flask import Flask, render_template, request 
import requests 

Initialize

Now let’s initialize our application as shown below.

app = Flask(__name__)

Create view

@app.route('/',methods=['GET','POST'])
def index():
    if request.method == "POST":
        location = request.form['location']
        url = "https://weatherapi-com.p.rapidapi.com/forecast.json"
        querystring = {"q": location,"days":"3"}

        headers = {
        "X-RapidAPI-Key": "YOUR API KEY",
        "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
        }

        response = requests.request("GET", url, headers=headers, params=querystring).json()

        for forecast in response["forecast"]["forecastday"][0]["hour"]:
            # Extract the time and temperature for each forecast hour
            time = forecast["time"]
            temp = forecast["temp_c"]
            humidity = forecast['humidity']
            wind = forecast['wind_kph']
            will_it_rain = forecast['will_it_rain']
            gust = forecast['gust_kph']
        return render_template("index.html",time=time,temp=temp,
                                            humidity=humidity,wind=wind,
                                            will_it_rain=will_it_rain, gust=gust)
    return render_template("index.html")

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


Create template

Now in the index.html file we create above insert the code below.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Weather App</title>
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        background-color: whitesmoke;
      }

      .card {
        background-color: white;
        box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        padding: 20px;
        text-align: center;
      }

      h1 {
        margin-top: 0;
      }
    </style>
  </head>
  <body>
    <div class="card">
      <h1>Weather App</h1>
      <form method="POST">
        <input type="text" name="location" id="location" placeholder="Enter location eg London" required>
        <input type="submit" value="Get weather">
      </form>
      {% if time %}
      <p>Current temperature: {{ temp }}°C</p>
      <p>Humidity: {{ humidity }}%</p>
      <p>Wind: {{ wind }} km/h</p>
      <p>Will it rain? {% if will_it_rain %}Yes{% else %}No{% endif %}</p>
      <p>Gust: {{ gust }} km/h</p>
      {% endif %}
    </div>
  </body>
</html>

Run

Now open your terminal and run the command below.

python3 app.py

Results

After running the above command open your browser at the address [ http://127.0.0.1:5000 ] and our app should appear as shown below.

There you have it. Thanks for reading. Happy Coding.

1 thought on “How to Build a Flask Weather App Using Python”

  1. Pingback: How to Build a Flask Rgb to Color Name App - bytexplain

Leave a Comment

Your email address will not be published. Required fields are marked *