RECENT POST

TOP POST

Crafting a Flask Weather Application with Weatherstack: Step-by-Step Guide

by | Nov 8, 2023

Introduction to Weatherstack

Weatherstack is a comprehensive weather data API providing real-time weather information for any location globally. From current conditions to historical data and forecasts, weatherstack delivers accurate and timely data.

Flask and PythonAnywhere are ideal for newcomers to web development, especially when working with APIs like Weatherstack. Flask, a “micro-framework,” offers a straightforward way to build web applications without unnecessary complexities. PythonAnywhere simplifies the deployment process. As a cloud-based platform tailored for Python, it requires no local server configurations and even offers a free tier perfect for small projects. Together, these tools allow beginners to focus on core web development concepts while gaining practical experience by building functional applications, such as weather apps.

In this Weatherstack tutorial, you’ll learn:

  • Understanding Weatherstack & Obtaining an API key:
    • Dive into what an API key is and how it grants access to Weatherstack’s rich data.
  • Setting Up a Flask application:
    • Discover Flask, a Python framework for web application development, and set up a basic web application.
  • Integrating Weatherstack with Flask:
    • Connect your Flask app to Weatherstack, enabling it to fetch and display weather data based on user inputs.
  • Deploying your Flask application on PythonAnywhere:
    • Learn the steps to host your Flask app online, making it accessible to users worldwide.
  • Enhancing Your Weather Application:
    • Explore ideas to refine and expand your application, adding valuable features and improving the user experience.

Getting Started: Signing Up for a Weatherstack API Key

  • Visit the Weatherstack website.
  • Register to get a FREE API key.
  • Post-registration, locate your API key on the dashboard. Preserve this; it’s essential for the upcoming steps.
Screenshot of Weatherstack API dashboard, get your free API key to begin building Weather Application

Deploying on PythonAnywhere

PythonAnywhere is an excellent platform tailored for Python developers, offering a streamlined process to get Python apps online.

  1. Registration and Dashboard:
    • If you’re new to PythonAnywhere, start by creating an account. 
    • Post login, you’ll access the Dashboard. For our needs, we’ll primarily work with the “Consoles” and “Web” tabs.
  1. Flask Integration & Web App Configuration:
    • Navigate to the “Web” tab.
    • Opt for “Add a new web app” and follow the on-screen instructions.
Screenshot of PythonAnywhere setup screen

  • When prompted, choose “Flask” and your Python version. If you are new to Python and Flask, just choose the latest version of Python, e.g. Python 3.10, listed last on the list.
Screenshot of configuring PythonAnywhere to Flask

Screenshot of configuring PythonAnywhere to the preferred version of Python

Screenshot of user directory generated by PythonAnywhere

  • Upon completion, you’ll be directed to the Web app configuration page. Here, ensure:
    • “Source code” points to your Flask script.
    • “Working directory” typically aligns with your source code’s directory.
Screenshot of where to find the source code directory on the Web tab of PythonAnywhere

  1. Upload Your Files:
    • Switch to the “Files” tab.
    • Upload your Flask script (often app.py or a similar name).
    • Make sure your HTML templates are inside a templates folder and upload that, too.
Screenshot of flask_app.py in PythonAnywhere files

Screenshot of where to save template directory for HTML files on PythonAnywhere

  1. Launching Your App:
    • Return to the “Web” tab.
    • Click the green “Reload” button.
    • Once reloaded, you’ll find a link at the page’s top. This link directs you to your Flask weather application, now live on the internet!

Flask Application Code

Here’s the code to set up a basic Flask application that interacts with the Weatherstack API:

# Required imports

from flask import Flask, request, render_template

import requests

# Create a Flask app instance

app = Flask(__name__)

# Function to fetch weather data for a given location

def get_weather_data(location):

    API_KEY = 'YOUR_WEATHERSTACK_API_KEY'

    BASE_URL = 'http://api.weatherstack.com/current'

    response = requests.get(BASE_URL, params={

        'access_key': API_KEY,

        'query': location

    })

    return response.json()

@app.route('/', methods=['GET', 'POST'])

def index():

    if request.method == 'POST':

        location = request.form['location']

        data = get_weather_data(location)

        return render_template('weather.html', data=data)

    return render_template('index.html')

if __name__ == '__main__':

    app.run(debug=True)

This code initiates a Flask application that interacts with the Weatherstack API. The primary function, get_weather_data, communicates with Weatherstack and fetches weather details for a given location. The @app.route decorator establishes the main endpoint. When users submit a location, the app retrieves the weather details and displays them via the weather.html template. If users visit the page without submitting any location, they’re presented with an index.html form to input their desired location.

HTML Templates

To display the data and interface, we utilize Flask’s templating system. Here are the templates:

index.html: This is the main page where users input a location.

Screenshot of index.html file being created in the templates directory

<!DOCTYPE html>

<html>

<head>

    <title>Weather App</title>

</head>

<body>

    <h1>Enter a location to get its weather</h1>

    <form action="/" method="post">

        <input type="text" name="location" placeholder="Enter location" required>

        <input type="submit" value="Get Weather">

    </form>

</body>

</html>

This page has a form where users can enter a location. Upon submission, the location is sent to the Flask app, which then retrieves the weather details for that location.

Screenshot of location London being entered into weather.html page

weather.html: Displays the weather data.

<!DOCTYPE html>

<html>

<head>

    <title>Weather Info</title>

</head>

<body>

    <h1>Weather for {{ data.location.name }}</h1>

    <p>Temperature: {{ data.current.temperature }}°C</p>

    <p>Weather Descriptions: {{ data.current.weather_descriptions[0] }}</p>

    <a href="/">Back to Home</a>

</body>

</html>

This page is shown once the user submits a location. It displays the location’s weather details fetched from the API.

Screenshot of weather results displayed on weatherstack app created on PythonAnywhere

Enhancing Your Weather Application

Your basic weather application is now functional. However, there’s always room for improvement. Consider integrating CSS frameworks like Bootstrap to uplift your app’s aesthetics. Ensure a smooth user experience by handling potential errors, such as invalid location inputs or maxing out API requests.

For users keen on extensive weather details, leverage Weatherstack’s forecasting capabilities. Offer a week-long forecast, enriching user insights. Additionally, delve into historical weather patterns using Weatherstack’s past data. Integrating visualization tools, such as Chart.js, can transform raw data into engaging and informative charts.

Enhanced weather.html file

<!DOCTYPE html>

<html>

<head>

    <title>Weather Info for {{ data.location.name }}</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            background-color: #f4f4f4;

            padding: 20px;

        }

        .weather-container {

            background-color: #ffffff;

            padding: 20px;

            border-radius: 8px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            max-width: 500px;

            margin: 40px auto;

        }

        h1 {

            color: #333;

            font-size: 24px;

            margin-bottom: 20px;

        }

        p {

            color: #666;

            font-size: 18px;

            margin-bottom: 10px;

        }

        a {

            display: inline-block;

            background-color: #3498db;

            color: #ffffff;

            padding: 10px 15px;

            border-radius: 5px;

            text-decoration: none;

            margin-top: 20px;

        }

        a:hover {

            background-color: #2980b9;

        }

    </style>

</head>

<body>

    <div class="weather-container">

        <h1>Weather for {{ data.location.name }}, {{ data.location.country }}</h1>

        <p>Temperature: {{ data.current.temperature }}°C</p>

        <p>Weather Descriptions: {{ data.current.weather_descriptions[0] }}</p>

        <p>Wind Speed: {{ data.current.wind_speed }} km/h</p>

        <p>Wind Direction: {{ data.current.wind_dir }}</p>

        <p>Humidity: {{ data.current.humidity }}%</p>

        <p>Visibility: {{ data.current.visibility }} km</p>

        <p>Pressure: {{ data.current.pressure }} hPa</p>

        <a href="/">Back to Home</a>

    </div>

</body>

</html>

In this enhanced version:

  • Styling: CSS has been added to give a cleaner and modern look to the weather.html page.
  • More Weather Details: Extra details have been included about wind speed, wind direction, humidity, visibility, and pressure to provide a thorough weather report to the user.
  • Location Detail: The country of the location has been added next to the city for more clarity.

Congratulations if you have managed to follow these steps. You’ve developed and deployed a Flask weather application integrated with Weatherstack. Building applications and seeing them come to life is a rewarding experience. Remember, every project you undertake helps in refining your skills, and there’s always something new to learn in the world of coding. Keep up the great work, and if you ever have more questions about how to use and deploy the Weatherstack API or need further guidance, don’t hesitate to ask our support team @ https://apilayer.com/support

Screenshot of weatherstack page, sign up for free to begin building Weather Applications.