# 小项目开发:基于Python和Flask的实时天气预报网页应用


背景介绍

本项目旨在通过Flask框架实现一个简单的网页应用,用户可输入城市名和日期,后端通过本地模拟API获取天气信息并返回结果。该系统要求具备两个关键功能:
1. 输入处理功能(文件读取)
2. 数据结构处理能力(JSON数据结构)
3. 网络请求功能(API调用)


思路分析

1. 网络请求实现

使用Flask的request对象接收POST请求,接收城市和日期参数。通过模拟API,构造包含天气信息的JSON数据并返回给前端。该部分的核心是:
– 构造JSON格式的响应数据
– 将数据封装为Flask路由返回

2. 文件读写处理

需要读取配置文件,例如weather_config.json,加载API密钥。文件读写涉及使用Python的os模块,确保配置文件的正确性。

3. 数据结构设计

采用JSON对象结构,包含城市名、日期、天气状况等字段。数据结构的抽象化和封装是实现该功能的关键,例如:

{
    "city": "北京",
    "date": "2023-04-05",
    "weather": "晴",
    "temperature": 22,
    "wind": "3级"
}

代码实现

1. 设置Flask服务器

app.py文件中,引入Flask并创建路由:

from flask import Flask, request, jsonify

app = Flask(__name__)

# 配置文件存储路径
config_file = 'weather_config.json'

# 读取配置文件
def load_config():
    with open(config_file, 'r') as f:
        config = f.read()
    return config

# 构造天气数据
def get_weather_data(city, date):
    # 示例数据(模拟API返回)
    return {
        "city": city,
        "date": date,
        "weather": "晴",
        "temperature": 22,
        "wind": "3级"
    }

# Flask路由处理
@app.route('/api/weather', methods=['POST'])
def get_weather():
    city = request.json.get('city')
    date = request.json.get('date')

    if city is None or date is None:
        return jsonify({'error': '请提供城市和日期'}), 400

    weather_data = get_weather_data(city, date)
    return jsonify(weather_data)

# 设置配置文件读取
@app.route('/config', methods=['GET'])
def load_config():
    config = load_config()
    return config

if __name__ == '__main__':
    app.run(debug=True)

2. 输出示例验证

输入:

curl -X POST -H "Content-Type: application/json" -d '{"city": "北京", "date": "2023-04-05"}' http://localhost:5000/api/weather

输出:

{
    "city": "北京",
    "date": "2023-04-05",
    "weather": "晴",
    "temperature": 22,
    "wind": "3级"
}

总结

本项目通过Python和Flask框架实现了以下功能:
1. 网络请求功能(使用Flask的request对象)
2. 文件读写能力(通过config文件配置API密钥)
3. 数据结构处理能力(JSON数据封装)

该系统可独立运行在本地环境,适合作为入门级的Web开发实践。通过该实现,可以系统学习文件处理、数据结构以及网络请求的相关内容。


学习价值
– 通过模拟API实现天气预报功能,提升对Web开发基础能力的理解
– 掌握文件读写和数据结构的处理逻辑,提升实际开发能力