Live Weather Forecast Flask App – Interesting Project – 2024

So guys in today’s blog we will create a Live Weather Forecast Flask App which takes a city name and returns various weather characteristics like Temperature in C, Temperature in F, Humidity, Wind, and many more.

Checkout the project video here – https://youtu.be/braycJCItA4

Sneak Peek at our Live Weather Forecast Flask App

Live Weather Forecast Flask App

So without any further due, let’s dive into it…

Step 1 – Importing Required Libraries

import json
import requests
from fpdf import FPDF
from flask import Flask,request,render_template

Step 2 – Getting API_KEY from RapidAPI

  • Get your API KEY, API HOST, and links from RapidAPI.
  • Open RapidAPI and search for WeatherAPI.com.
  • Now click on Subscribe to Test and Subscribe to the Basic Plan which is FREE 🙂
API_KEY = "YOUR API KEY"
API_HOST = "weatherapi-com.p.rapidapi.com"
API_URL = "https://weatherapi-com.p.rapidapi.com/current.json"

app = Flask(__name__)
Machine Learning Projects
  • Now copy your API_KEY, API_HOST, and URL from here.
  • Finally, define the Flask app.

Step 3 – Defining the route functions for our Live Weather Forecast Flask App

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/predict_weather',methods=['POST'])
def predict_weather():
    if request.method == 'POST':
        q = request.form['location']
        url = API_URL
        querystring = {"q":q}
        headers = {
            "X-RapidAPI-Key": API_KEY,
            "X-RapidAPI-Host": API_HOST
        }
        try:
            response = requests.request("GET", url, headers=headers, params=querystring)
            json_data = json.loads(response.text)
            
            name = json_data['location']['name']
            region = json_data['location']['region']
            country = json_data['location']['country']
            lat = json_data['location']['lat']
            lon = json_data['location']['lon']
            tz_id = json_data['location']['tz_id']
            localtime_epoch = json_data['location']['localtime_epoch']
            localtime = json_data['location']['localtime']
            last_updated_epoch = json_data['current']['last_updated_epoch']
            last_updated = json_data['current']['last_updated']
            temp_c = json_data['current']['temp_c']
            temp_f = json_data['current']['temp_f']
            is_day = json_data['current']['is_day']
            condition_text = json_data['current']['condition']['text']
            condition_icon = json_data['current']['condition']['icon']
            wind_mph = json_data['current']['wind_mph']
            wind_kph = json_data['current']['wind_kph']
            wind_degree = json_data['current']['wind_degree']
            wind_dir = json_data['current']['wind_dir']
            pressure_mb	 = json_data['current']['pressure_mb']
            pressure_in = json_data['current']['pressure_in']
            precip_mm = json_data['current']['precip_mm']
            precip_in = json_data['current']['precip_in']
            humidity = json_data['current']['humidity']
            cloud = json_data['current']['cloud']
            feelslike_c = json_data['current']['feelslike_c']
            feelslike_f = json_data['current']['feelslike_f']
            vis_km = json_data['current']['vis_km']
            vis_miles = json_data['current']['vis_miles']
            uv = json_data['current']['uv']
            gust_mph = json_data['current']['gust_mph']
            gust_kph = json_data['current']['gust_kph']

            return render_template('home.html',name=name,region=region,country=country,lat=lat,lon=lon,tz_id=tz_id,
            localtime_epoch=localtime_epoch,localtime=localtime,last_updated_epoch=last_updated_epoch,last_updated=last_updated,
            temp_c=temp_c,temp_f=temp_f,is_day=is_day,condition_text=condition_text,condition_icon=condition_icon,wind_mph=wind_mph,
            wind_kph=wind_kph,wind_degree=wind_degree,wind_dir=wind_dir,pressure_mb=pressure_mb,pressure_in=pressure_in,precip_mm=precip_mm,
       precip_in=precip_in,humidity=humidity,cloud=cloud,feelslike_c=feelslike_c,feelslike_f=feelslike_f,vis_km=vis_km,
            vis_miles=vis_miles,uv=uv,gust_mph=gust_mph,gust_kph=gust_kph)

        except:
            return render_template('home.html',error='Please enter a correct Place name...')

if __name__ == '__main__':
    app.run(debug=True)
  • Here we are simply hitting the API with a location name and catching the response from that API.
  • That response sends back many parameters which we are reading.
Machine Learning Projects

For Delhi we get a result like the following:

{"location":{"name":"Delhi","region":"Delhi","country":"India","lat":28.67,"lon":77.22,"tz_id":"Asia/Kolkata","localtime_epoch":1661504566,"localtime":"2022-08-26 14:32"},"current":{"last_updated_epoch":1661504400,"last_updated":"2022-08-26 14:30","temp_c":33.0,"temp_f":91.4,"is_day":1,"condition":{"text":"Mist","icon":"//cdn.weatherapi.com/weather/64x64/day/143.png","code":1030},"wind_mph":8.1,"wind_kph":13.0,"wind_degree":310,"wind_dir":"NW","pressure_mb":1004.0,"pressure_in":29.65,"precip_mm":0.0,"precip_in":0.0,"humidity":59,"cloud":75,"feelslike_c":34.1,"feelslike_f":93.4,"vis_km":5.0,"vis_miles":3.0,"uv":9.0,"gust_mph":13.2,"gust_kph":21.2}}

Open this JSON Viewer to see the JSON Tree structure…

Snapshot of our Live Weather Forecast Flask App

Live Weather Forecast Flask App
Snapshot of our Final App

Source Codes for the Live Weather Forecast Flask App…

app.py

import json
import requests
from fpdf import FPDF
from flask import Flask,request,render_template

API_KEY = "YOUR API KEY HERE"
API_HOST = "weatherapi-com.p.rapidapi.com"
API_URL = "https://weatherapi-com.p.rapidapi.com/current.json"

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/predict_weather',methods=['POST'])
def predict_weather():
    if request.method == 'POST':
        q = request.form['location']
        url = API_URL
        querystring = {"q":q}
        headers = {
            "X-RapidAPI-Key": API_KEY,
            "X-RapidAPI-Host": API_HOST
        }
        try:
            response = requests.request("GET", url, headers=headers, params=querystring)
            json_data = json.loads(response.text)
            
            name = json_data['location']['name']
            region = json_data['location']['region']
            country = json_data['location']['country']
            lat = json_data['location']['lat']
            lon = json_data['location']['lon']
            tz_id = json_data['location']['tz_id']
            localtime_epoch = json_data['location']['localtime_epoch']
            localtime = json_data['location']['localtime']
            last_updated_epoch = json_data['current']['last_updated_epoch']
            last_updated = json_data['current']['last_updated']
            temp_c = json_data['current']['temp_c']
            temp_f = json_data['current']['temp_f']
            is_day = json_data['current']['is_day']
            condition_text = json_data['current']['condition']['text']
            condition_icon = json_data['current']['condition']['icon']
            wind_mph = json_data['current']['wind_mph']
            wind_kph = json_data['current']['wind_kph']
            wind_degree = json_data['current']['wind_degree']
            wind_dir = json_data['current']['wind_dir']
            pressure_mb	 = json_data['current']['pressure_mb']
            pressure_in = json_data['current']['pressure_in']
            precip_mm = json_data['current']['precip_mm']
            precip_in = json_data['current']['precip_in']
            humidity = json_data['current']['humidity']
            cloud = json_data['current']['cloud']
            feelslike_c = json_data['current']['feelslike_c']
            feelslike_f = json_data['current']['feelslike_f']
            vis_km = json_data['current']['vis_km']
            vis_miles = json_data['current']['vis_miles']
            uv = json_data['current']['uv']
            gust_mph = json_data['current']['gust_mph']
            gust_kph = json_data['current']['gust_kph']

            return render_template('home.html',name=name,region=region,country=country,lat=lat,lon=lon,tz_id=tz_id,
            localtime_epoch=localtime_epoch,localtime=localtime,last_updated_epoch=last_updated_epoch,last_updated=last_updated,
            temp_c=temp_c,temp_f=temp_f,is_day=is_day,condition_text=condition_text,condition_icon=condition_icon,wind_mph=wind_mph,
            wind_kph=wind_kph,wind_degree=wind_degree,wind_dir=wind_dir,pressure_mb=pressure_mb,pressure_in=pressure_in,precip_mm=precip_mm,
            precip_in=precip_in,humidity=humidity,cloud=cloud,feelslike_c=feelslike_c,feelslike_f=feelslike_f,vis_km=vis_km,
            vis_miles=vis_miles,uv=uv,gust_mph=gust_mph,gust_kph=gust_kph)

        except:
            return render_template('home.html',error='Please enter a correct Place name...')


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

home.html

<!doctype html>
<html lang="en">

<style type='text/css'>
    body{
    background-image: url('https://i.pinimg.com/originals/0e/f3/bb/0ef3bb66d9216fffcea9022628f7bb26.gif');
    background-size: cover;
    font-family: sans-serif;
    margin-top: 40px;
    height: 100vh;
    padding:0;
    margin:0;
    }

    .regform {
        background-color: rgb(0, 0, 0, 0.8);
        margin: 0px 20px 0px 20px;
        color: #FFFFFF;
        padding: 10px 0px 10px 0px;
        text-align: center;
        border-radius: 15px 15px 0px 0px;

    }

    .main-form {
        margin: 0px 20px 0px 20px;
        background-color: rgb(0, 0, 0, 0.7);
        padding-top: 20px;
        padding-left: 50px;
        padding-right: 50px;
        padding-bottom: 20px;
        color: #FFFFFF;
    }

    .details{
        font-weight: bold;
        font-size: 17px;
    }
</style>


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Live Weather Forecast</title>
</head>

<body>

    <div class='regform mt-3'>
        <h1>Live Weather Forecast</h1>
    </div>

    <form action='/predict_weather' class='main-form' method="POST">

        <div class='text-center'>
            <input type="text" id="location" name='location' placeholder="Enter the Location" style="font-size:20px;margin-bottom:10px;width: 700px;">
            <button type='submit' class='btn btn-outline-success'
                style="margin-top:10px;margin-bottom:10px;width: 700px;"> What's the Weather
            </button>
        </div>

    </form>

    {% if error %}
    <div class='text-center'style="margin: 0px 20px 0px 20px;background-color: rgb(0, 0, 0, 0.7);color: #FFFFFF; padding-bottom: 20px;">
    <h2>{{ error }}</h2>
    </div>

    {% endif %}

    {% if name %}
    <div style="margin: 0px 20px 0px 20px;background-color: rgb(0, 0, 0, 0.7);color: #FFFFFF; padding-bottom: 20px;">
        <div class="row text-center">
            <h1>Current Temperature in {{ name }}</h1>
        </div>

        <div class="row text-center" style="margin-top: 10px;">
            <h2>{{ temp_c }}°C / {{ temp_f }}°F <img src='{{ condition_icon }}'></h2>
            <p><i>Last Updated- {{ last_updated }}</i></p>
        </div>

        <div class="row text-center" style="margin-top: 20px;">
            <div class="details col">
                <p>Region: {{ region }} / {{ country }}</p>
            </div>
            <div class="details col">
                <p>Lattitude: {{ lat }}°</p>
            </div>
            <div class="details col">
                <p>Longitude: {{ lon }}°</p>
            </div>
            <div class="details col">
                <p>TimeZone: {{ tz_id }}</p>
            </div>
            <div class="details col">
                <p>LocalTime: {{ localtime }}</p>
            </div>
        </div>
        
        <div class="row text-center" style="margin-top: 20px;">
            <div class="details col">
                <p>Condition: {{ condition_text }}</p>
            </div>
            <div class="details col">
                <p>Wind: {{ wind_mph }}mph / {{ wind_kph }}kph</p>
            </div>
            <div class="details col">
                <p>Wind Direction: {{ wind_degree }}° {{ wind_dir }} </p>
            </div>
            <div class="details col">
                <p>Pressure: {{ pressure_mb }}mb / {{ pressure_in }}in</p>
            </div>
            <div class="details col">
                <p>Precip: {{ precip_mm }}mm / {{ precip_in }}in</p>
            </div>
        </div>
        
        <div class="row text-center" style="margin-top: 20px;">
            <div class="details col">
                <p>Humidity: {{ humidity }}</p>
            </div>
            <div class="details col">
                <p>Feelslike: {{ feelslike_c }}°C / {{ feelslike_f }}°F</p>
            </div>
            <div class="details col">
                <p>Visibility: {{ vis_km }}km / {{ vis_miles }}miles</p>
            </div>
            <div class="details col">
                <p>UV: {{ uv }}</p>
            </div>
            <div class="details col">
                <p>Gust mph: {{ gust_mph }}mph / {{ gust_kph }}kph</p>
            </div>
        </div>
    </div>
    {% endif %}

</body>

</html>

And this is how you can build a Live Weather Forecast Flask App…

Working of our App

Download Source Code

You can deploy it online also: How to Deploy a Flask app online using Pythonanywhere

So this is all for this blog folks. Thanks for reading it and I hope you are taking something with you after reading this and till the next time …

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projects, and Flask projects at machinelearningprojects.net.

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

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