Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 77 ยท Projects

Project: Weather App

Build a Django weather app that calls an external API: a service layer, a form, timeouts and error handling, caching, and tests with a fake HTTP client, all runnable in the browser.

Most real applications talk to other services: payment providers, maps, email, weather. This project builds a small weather app, and the focus is not the weather. It is the habits that make any external-API feature reliable: keep the HTTP code in one place, always set a timeout, turn failures into friendly messages, cache answers, and make the whole thing testable without the internet.

The app has one page. The visitor types a city, Django asks a weather service for the current conditions, and the page shows the temperature, a description and the wind speed.

The plan

flowchart LR
    U["Visitor<br/>types a city"] --> V["View<br/>validates the form"]
    V --> K{"In cache?"}
    K -- yes --> T["Template"]
    K -- no --> S["WeatherClient<br/>(service layer)"]
    S --> G["Geocoding API<br/>city to lat/lon"]
    S --> F["Forecast API<br/>current weather"]
    S --> C["Cache result<br/>10 minutes"]
    C --> T
    S -. "error" .-> E["Friendly message"]
    E --> T

The view never talks HTTP itself. It asks the service, which is the only code that knows about URLs, parameters and the network.

We use Open-Meteo, a free weather service that needs no API key, with two endpoints: a geocoding search (city name to latitude and longitude) and a forecast endpoint (coordinates to current conditions). Most weather APIs, for example OpenWeatherMap, need a key you keep in an environment variable (see Projects, Apps and Settings and Deploying Django). The structure below is the same either way.

Step 1: the service layer

Put everything that touches the outside world in one class, for three reasons: the view stays short, errors are translated in one place, and tests can replace the network.

Three design decisions matter:

  1. Dependency injection. WeatherClient receives an http_get function. In production that is a thin wrapper around requests.get; in tests and in this lesson it is a fake that returns canned JSON.
  2. Your own exceptions. The view should not know about requests.Timeout or JSON shapes. It catches CityNotFound and ServiceUnavailable.
  3. A timeout on every call. Without one, a hung server can freeze a worker forever.

The real network function is small:

Python
# weather/http.py (read-only; pip install requests)
import requests

def http_get(url, params, timeout):
    try:
        response = requests.get(url, params=params, timeout=timeout)
        response.raise_for_status()                # 4xx and 5xx become exceptions
        return response.json()
    except (requests.Timeout, requests.ConnectionError) as exc:
        raise TimeoutError(str(exc)) from exc      # one error type for "could not reach it"

Everything else is plain Python. The next example runs the service with a fake http_get and a table of weather descriptions (the service reports conditions as numeric WMO codes such as 3 for "Overcast"), covering the success path and both failure paths.

Python The service layer with a fake HTTP function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output shows two upstream calls for London (geocode, then forecast), one for the unknown city (the geocoder returned no results, so there is nothing to forecast), and a timeout translated into ServiceUnavailable before any forecast was requested. Notice that an unknown city is not an HTTP error: the geocoding API answers 200 OK with no results. Always read the API's documentation for how it reports "nothing found" and "you did something wrong".

Step 2: the form and the view

A search box is a form, and you already know Django forms. Use GET rather than POST: a search has no side effects, and a GET URL (/?city=London) can be bookmarked and shared. With a GET form, request.GET or None means "unbound when there is no query string," so the empty page shows no errors.

The view's flow is:

  1. Validate the city with the form.
  2. Look in the cache (a 10-minute entry per city: weather does not change by the second, and most APIs limit how often you may call them).
  3. On a miss, call the service; catch CityNotFound (status 404) and ServiceUnavailable (503) and show a message instead of crashing.
  4. Render the template with the weather, the error, or neither.

Cache plain data, not custom objects: asdict(weather) stores a dictionary that pickles and serializes on every cache backend, while a class defined in your project can break on cache backends that cannot import it. In production you would use Redis or Memcached (see Caching); the local-memory backend below behaves the same for this lesson.

Python The whole app: form, view, cache and error pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the six lines like a test report. The cache made the second London request free (upstream calls: []), and it hit because the form's strip=True cleaned the input and the key was lower-cased, so london and London share one entry. The unknown city and the timeout produced friendly pages with the right HTTP status (404 and 503) and did not populate the cache, so the next try calls the service again. The empty search never reached the service at all.

Step 3: tests without the internet

Because the client takes http_get as an argument, a test passes a stub. No network, no flakiness, no API quota used:

Python
# weather/tests.py (read-only)
from django.test import TestCase
from unittest import mock

from .services import CityNotFound, ServiceUnavailable, WeatherClient


class WeatherClientTests(TestCase):
    def test_unknown_city_raises(self):
        stub = mock.Mock(return_value={})                  # no "results" key
        with self.assertRaises(CityNotFound):
            WeatherClient(stub).current("Atlantis")

    def test_view_shows_error_when_service_is_down(self):
        with mock.patch("weather.views.get_client") as factory:
            factory.return_value.current.side_effect = ServiceUnavailable("slow")
            response = self.client.get("/", {"city": "London"})
        self.assertEqual(response.status_code, 503)

Patch the function where it is used (weather.views.get_client), not where it is defined. For deeper patterns see Testing Patterns: Factories, Mocks and pytest-django.

Where to take it next

  • Retries. For a short network glitch, retry once or twice with a small delay (requests with urllib3.util.Retry, or the tenacity package). Do not retry on 404.
  • Async. An async view with httpx.AsyncClient can call both endpoints concurrently under ASGI (see Async Django); do not call blocking requests inside an async def view.
  • A forecast. Ask the forecast endpoint for daily= values and show a five-day table.
  • Search history. Store each lookup in a model for a "recent searches" list, and use signals or a task queue if you later want to refresh popular cities in the background.
  • Units and language. Offer Celsius or Fahrenheit through a form field and pass it to the API.
  • Rate limits. Cache aggressively and respect the provider's terms. If the API needs a key, keep it in an environment variable and never in the template or JavaScript.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does WeatherClient receive an http_get function instead of calling requests directly?

    Injecting the network function keeps the HTTP details in one place and lets you test every path without the internet.
  2. 2. What should you always set when calling an external API with requests?

    Without a timeout, a slow or hung server can block your worker indefinitely. Treat a timeout as an expected failure and show a friendly message.
  3. 3. Why cache the weather per city for ten minutes?

    Conditions change slowly, and repeated identical requests waste time and quota.
  4. 4. Which status code does the view return when the weather service times out?

    503 tells clients and monitoring that a dependency is temporarily unavailable. The page still renders a friendly message.

Summary

  • Keep all code that talks to an external service in one service class, with its own exceptions, so views stay small.
  • Always set a timeout, read how the API reports errors (an unknown city may be a 200 with no results), and show friendly messages.
  • Validate input with a form, use GET for searches, and cache results by a normalized key; cache plain data.
  • Inject the HTTP function so tests use a fake; patch where the name is used.
  • Keep API keys in environment variables and consider retries, async views and background refreshes as the app grows.

Next: Project: Multi-Role Management System.