标签 web 下的文章

OIP-C-Flask.jpeg

Flask网络应用 - 天气应用

Flask官方文档
使用Flask框架构建一个简单的天气网络应用,获取指定城市的天气信息

需要安装flask
pip install flask -i https://pypi.tuna.tsinghua.edu.cn/simple
openweathermap 免费的API服务,获取API_KEY
  • 新建一个目录比如weather_app
  • 在该目录下面再建一个子目录templates
  • 在目录weather_app下面新建文件weather_app.py,内容如下:

导入flask组件

from flask import Flask, render_template, request
import requests

app初始化


app = Flask(__name__)
API_KEY = '6a645a2f6bd3be51f5a30b36577a81'  ## 替换为你的 OpenWeatherMap API 密钥

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/weather', methods=['POST'])
def weather():
    city = request.form['city']
    weather_data = get_weather_data(city)
    if weather_data:
        return render_template('weather.html', city=city, weather=weather_data)
    else:
        return render_template('error.html', message='无法获取天气信息')

def get_weather_data(city):
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric&lang=zh_cn'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = {
            'description': data['weather'][0]['description'],
            'temperature': data['main']['temp'],
            'humidity': data['main']['humidity'],
            'wind_speed': data['wind']['speed'],
        }
        return weather
    else:
        return None

if __name__ == '__main__':
    app.run(debug=True)
  • 在目录templates下面新建三个html模板文件:index.html, weather.html, error.html

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>天气应用</title>
</head>
<body>
    <h1>天气应用</h1>
    <form action="/weather" method="post">
        <label for="city">输入城市名:</label>
        <input type="text" id="city" name="city" required>
        <button type="submit">获取天气</button>
    </form>
</body>
</html>

weather.html:

<!DOCTYPE html>
<html>
<head>
    <title>{{ city }}的天气</title>
</head>
<body>
    <h1>{{ city }}的天气</h1>
    <p>天气描述:{{ weather.description }}</p>
    <p>温度:{{ weather.temperature }}°C</p>
    <p>湿度:{{ weather.humidity }}%</p>
    <p>风速:{{ weather.wind_speed }} m/s</p>
</body>
</html>

error.html:

<!DOCTYPE html>
<html>
<head>
    <title>错误</title>
</head>
<body>
    <h1>发生错误</h1>
    <p>{{ message }}</p>
</body>
</html>