<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 ℃ <br/>
<b>Humidity</b>: 60 %
</p>
</body>
</html>
$ python3 -m http.server --cgi 8000
The server can be stopped by Ctrl+C if needed.
http://localhost:8000/weather.html
#! /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))
$ python3 cgi-bin/weather.py
<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> ℃ <br/>
<b>Humidity</b>: <span id="humidity">0</span> %
</p>
<p>
<input type="text" id="city_input">
<button type="submit" name="submit">Show</button>
</p>
<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>
<button type="submit" name="submit" onclick="showWeatherInfo()">Show</button>
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.
$ python3 cgi-bin/weather.py
You may have to install the "requests" package with the following command.
$ pip3 install requests
city = data["name"]
icon = data["weather"][0]["icon"]
temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
print(jsonText)
var city_input = document.getElementById("city_input").value;
var url = encodeURI("/cgi-bin/weather.py?city=" + city_input);
import cgi
form = cgi.FieldStorage()
city_name = form.getvalue('city','Kyoto')
Copyright © 2020-2022 Hideyuki Takada