Building a weather information site

Setting up a Web server

  1. Make sure that Python3 is installed on your Mac.
  2. Create a folder to store files for this project.
  3. Create a file named "weather.html" with the following content under the folder created above.
    <html>
      <head>
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
      </head>
    	<body>
    	    <h1>Weather Information</h1>
    	    <img src="http://openweathermap.org/img/w/02d.png" width="64">
    	    <p>
    	      <b>City:</b> Kyoto <br/>
    	      <b>Temperature</b>: 30 &#8451; <br/>
    	      <b>Humidity</b>: 60 %
    	    </p>
        </body>
    </html>
    
  4. Open a window of Terminal and change the current directory to the folder created above.
  5. Start the Python Web server with the following command.
    $ python3 -m http.server --cgi 8000
    
    The server can be stopped by Ctrl+C if needed.
  6. Access to the Web server with the following URL on your Web browser.

    http://localhost:8000/weather.html

Building a server side code that returns the weather information

  1. Create a folder named "cgi-bin" under the folder created above.
  2. Create a file named "weather.py" with the following content under the "cgi-bin" folder. This program outputs a dummy weather information in the JSON format.
    #! /usr/bin/env python3
    
    import json
    
    print("Content-type: text/json\n")
    
    weather = {"city": "Kyoto", "icon": "02d", "temp": 30, "humidity": 60}
    print(json.dumps(weather))
    
  3. Run this program with the following command and check how it works.
    $ python3 cgi-bin/weather.py
    

Adding a dynamic content to the HTML file

  1. Modify the HTML file so that a dynamic content can be displayed (by adding the "span" tags and giving them IDs for the dynamic parts of the page).
    	    <h1>Weather Information</h1>
    	    <img id="icon" src="" width="64">
    	    <p>
    	      <b>City:</b> <span id="city"> City </span><br/>
    	      <b>Temperature</b>: <span id="temp">0</span> &#8451; <br/>
    	      <b>Humidity</b>: <span id="humidity">0</span> %
    	    </p>
    
  2. Also add a text input area to specify a city name and a button to show.
    	    <p>
    	      <input type="text" id="city_input">
    	      <button type="submit" name="submit">Show</button>
    	    </p>
    
  3. Check if this page is correctly shown on the browser.

Receiving the weather information from the server and changes the page content

  1. Add the following JavaScript code inside the <head> element of the HTML file.
    	  <script type="text/javascript">
    		var request = new XMLHttpRequest();
    		function showWeatherInfo() {
    			var url = "/cgi-bin/weather.py";
    			url = encodeURI(url);
    			request.open("GET", url, true);
    			request.onreadystatechange = updatePage;
    			request.send(null);
    		}
    		function updatePage() {
    			if (request.readyState == 4) {
    				if (request.status == 200) {
    					var replyDoc = JSON.parse(request.responseText);
    					var city = replyDoc.city;
    					var cityElm = document.getElementById("city");
    					cityElm.removeChild(cityElm.firstChild);
        				cityElm.appendChild(document.createTextNode(city));
        				var icon = replyDoc.icon;
        				var imgElem = document.getElementById("icon");
        				imgElem.src = "http://openweathermap.org/img/w/" + icon + ".png";
    				}
    			}
    		}
    	  </script>	
    
  2. Change the button element as follows to call the showWeatherInfo() function of the JavaScript code.
    <button type="submit" name="submit" onclick="showWeatherInfo()">Show</button>
    
  3. Press the "Show" button on the page and check if a weather icon returned from the server is displayed on the page. The weather information displayed is still dummy.
  4. Change the JavaScript code to show temperature and humidity values and check if it works correctly.

Obtaining the weather information from the OpenWeatherMap API

  1. The weather information for a specified city can be obtained with the following code. Add these lines of code to the server side python program.
    import requests
    import json
    
    city_name = "Kyoto"
    API_KEY = "d01ed74f13d285ba9f785fb49335bf3a"
    
    api = "http://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&APPID={key}"
    
    url = api.format(city = city_name, key = API_KEY)
    response = requests.get(url)
    data = response.json()
    jsonText = json.dumps(data, indent=4)
    
    print(jsonText)
    
    You may get your own API key at https://openweathermap.org/api.
  2. Run this code with the following command and see what content is returned from the OpenWeatherMap API.
    $ python3 cgi-bin/weather.py
    
    You may have to install the "requests" package with the following command.
    $ pip3 install requests
    

Extracting the city name, weather icon, temperature and humidity data from the JSON data

  1. Content of the JSON data returned from the OpenWeatherMap API can be extracted with the following code.
    city = data["name"]
    icon = data["weather"][0]["icon"]
    temp = data["main"]["temp"]
    humidity = data["main"]["humidity"]
    
  2. Change the python code to return the weather information (instead of the dummy one). Be sure to remove the following line.
    print(jsonText)
    

Adding a function to specify a city name

  1. Changing the JavaScript code in specifying URL as follows will send the city name input by a user.
    var city_input = document.getElementById("city_input").value;
    var url = encodeURI("/cgi-bin/weather.py?city=" + city_input);
    
  2. A city name input on a browser can be obtained with the following code in the python code.
    import cgi
    
    form = cgi.FieldStorage()
    city_name = form.getvalue('city','Kyoto')
    
  3. Check if the weather information of a specified city is shown correctly.

Extending the application

Add new functions as you like.

Copyright © 2020-2022 Hideyuki Takada