在我们之前的 Python 教程中,我们已经解释了如何 用Python创建你的第一个网络应用程序.在本教程中,我们将解释如何用Python开发天气应用程序。
创建天气应用程序是为了提供任何地点的天气细节。在这里,我们将使用Python和Flask创建一个天气应用程序,以提供任何城市的当前天气细节和温度。
在本教程中,我们将使用Open Weather Map API来获取天气细节。
因此,让我们继续在Python中开发天气应用程序。
需要的模块
- Flask:它是一个轻量级的WSGI网络应用框架,用于使用Python创建网络应用。它可以用下面的命令来安装。
pip install Flask
- 请求。我们需要安装这个模块。该模块允许使用Python进行HTTP请求。它可以用下面的命令安装。
pip install requests
获取API密钥
由于我们将使用第三方天气API来获取天气细节,所以我们需要访问OpenWeatherMap来获取API密钥,以便在这个应用程序中使用。
生成API密钥的步骤。
- 登录到Open Weather Map
- 然后转到 我的API密钥部分。然后点击 API密钥部分,在那里你会得到默认的API密钥。你也可以创建新的API密钥。
- 然后去到 API部分,获得在你的脚本中使用的API链接。 api.openweathermap.org/data/2.5/weather?q={城市名称}&appid={API密钥}。
开发天气应用程序
在安装完所需的模块和获得API密钥后,我们将创建app.py Python文件。
然后我们将导入Flask 和requests 模块。我们还将使用Flask的辅助工具request 和render_template 来发布数据和渲染模板。
from flask import Flask, request, render_template
import requests
然后我们将创建一个flask应用程序的实例。
app = Flask(__name__)
然后我们将创建路由。我们将在这里处理Get 和POST 两个请求。
@app.route('/', methods =["GET", "POST"])
def index():
现在我们将向openweathermap API发出一个GET HTTP请求,以获得天气的JSON数据。在这里,我们将从表单中获取城市名称,因为我们将允许用户输入城市来查找天气细节。
if request.method == "POST":
cityName = request.form.get("cityName")
weatherApiKey = 'Your API Key Goes Here'
url = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=" + weatherApiKey
weatherData = requests.get(url).json()
现在我们调用render_template 函数来调用模板文件和传递天气JSON数据来渲染。
return render_template('index.html', data = weatherData, cityName = cityName, error = error)
这里是完整的app.py 文件。
from flask import Flask, request, render_template
import requests
app = Flask(__name__)
@app.route('/', methods =["GET", "POST"])
def index():
weatherData = ''
error = 0
cityName = ''
if request.method == "POST":
cityName = request.form.get("cityName")
if cityName:
weatherApiKey = 'Your API Key Goes Here'
url = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=" + weatherApiKey
weatherData = requests.get(url).json()
else:
error = 1
return render_template('index.html', data = weatherData, cityName = cityName, error = error)
if __name__ == "__main__":
app.run()
由于我们正在使用HTML表单进行城市天气搜索,并在模板文件中显示细节。因此,我们将在项目目录中创建一个文件夹templates ,并创建index.html 文件。
然后我们将创建以下HTML来创建FORM,并渲染API调用后传递的天气数据。
这里是完整的index.html 文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Weather App using Flask in Python</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br><br><br>
<div class="row"><h2>Weather App using Flask in Python</h2></div>
<br>
<div class="row">
<p>Get weather details of any city around the world.</p>
</div>
<div class="row">
{% block content %}
<form action="{{ url_for("index")}}" method="post">
<div class="form-group">
<label for="cityName">City Name:</label>
<input type="text" id="cityName" name="cityName" value="{{cityName}}" placeholder="City Name">
<button class="submit">Find</button>
{% if error is defined and error %}
<br><br><span class="alert alert-danger">Error: Please enter valid city name.</span></br>
{% endif %}
</div>
{% endblock %}
{% if data is defined and data %}
<table class="table table-bordered">
<thead>
<tr>
<th>Country Code</th>
<th>Coordinate</th>
<th>temperature</th>
<th>Pressure</th>
<th>Humidity</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bg-success">{{ data.sys.country }}</td>
<td class="bg-info">{{data.coord.lon }} {{data.coord.lat}}</td>
<td class="bg-danger">{{data.main.temp }} k</td>
<td class="bg-warning">{{data.main.pressure}}</td>
<td class="bg-primary">{{data.main.humidity}}</td>
</tr>
</tbody>
</table>
{% endif %}
</div>
</div>
</body>
</html>