要做个小程序 要做个小程序怎么弄

小编 09-30 9

当然可以,下面是一个简单的小程序设计概念,我们将创建一个名为“每日天气”的小程序,用户可以通过它查看当前的天气情况,这个小程序将使用Python语言,并利用OpenWeatherMap API来获取天气数据。

要做个小程序 要做个小程序怎么弄

1. 项目概述

名称: 每日天气

功能:

- 显示当前日期和时间

- 获取并显示用户所在位置的天气信息

- 提供未来几天的天气预报

技术栈:

- Python

- Flask(用于创建web服务)

- OpenWeatherMap API(获取天气数据)

2. 环境搭建

确保你的计算机上安装了Python和pip,安装Flask和requests库。

pip install Flask requests

3. 获取API密钥

访问OpenWeatherMap官网,注册账户并获取API密钥。

4. 编写代码

a. Flask应用结构

/weather_app
    /templates
        home.html
    app.py

b. app.py

from flask import Flask, render_template, request
import requests
import datetime
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
    weather_data = {}
    if request.method == 'POST':
        # 获取用户输入的城市名
        city = request.form.get('city')
        api_key = '你的API密钥'
        url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric'
        response = requests.get(url)
        data = response.json()
        if response.status_code == 200:
            weather_data = {
                'city': city,
                'temperature': data['main']['temp'],
                'weather': data['weather'][0]['description'],
                'humidity': data['main']['humidity'],
                'pressure': data['main']['pressure']
            }
        else:
            weather_data = {'error': 'City not found'}
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return render_template('home.html', current_time=current_time, weather=weather_data)
if __name__ == '__main__':
    app.run(debug=True)

c. home.html

<!DOCTYPE html>
<html>
<head>
    <title>每日天气</title>
</head>
<body>
    <h1>每日天气</h1>
    <p>当前时间: {{ current_time }}</p>
    <form action="/" method="post">
        <input type="text" name="city" placeholder="输入城市名" required>
        <button type="submit">查询天气</button>
    </form>
    {% if weather %}
        <div>
            <h2>天气信息</h2>
            <p>城市: {{ weather.city }}</p>
            <p>温度: {{ weather.temperature }}°C</p>
            <p>天气: {{ weather.weather }}</p>
            <p>湿度: {{ weather.humidity }}%</p>
            <p>气压: {{ weather.pressure }} hPa</p>
        </div>
    {% elif weather.error %}
        <p>{{ weather.error }}</p>
    {% endif %}
</body>
</html>

5. 运行应用

在命令行中运行以下命令启动Flask应用:

python app.py

现在,你可以在浏览器中访问 http://127.0.0.1:5000/ 来查看你的“每日天气”小程序。

6. 扩展功能

- 添加用户位置自动检测功能。

- 提供未来几天的天气预报。

- 创建一个更复杂的前端界面。

这个小程序是一个基础的起点,你可以根据需要添加更多功能和改进。

The End
微信