欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > create-a-weather-app-using-flask-python

create-a-weather-app-using-flask-python

2025/9/19 10:43:24 来源:https://blog.csdn.net/m0_63287589/article/details/144915496  浏览:    关键词:create-a-weather-app-using-flask-python

使用 Flask | Python 创建天气应用程序

原文:https://www . geesforgeks . org/create-a-weather-app-use-flask-python/

先决条件: 烧瓶安装

Flask 是一个用 Python 编写的轻量级框架。它是轻量级的,因为它不需要特定的工具或库,并且允许快速的 web 开发。今天我们将使用 flask 作为 web 框架创建一个天气应用程序。这个天气网络应用程序将提供搜索到的城市的最新天气信息。

基本设置:

创建一个文件,并将其命名为

创建文件的 Linux 命令

touch weather.py 

现在,用文件名index.html创建一个文件夹模板

Linux 命令创建一个文件夹和一个文件

 mkdir templates && cd templates && touch index.html 

项目文件夹看起来像:
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

编辑文件:
从天气 API 中使用自己的 API 密钥,并将其放入 API 变量中。现在编辑weather.py文件。

from flask import Flask, render_template, request# import json to load JSON data to a python dictionary
import json# urllib.request to make a request to api
import urllib.requestapp = Flask(__name__)@app.route('/', methods =['POST', 'GET'])
def weather():if request.method == 'POST':city = request.form['city']else:# for default name mathuracity = 'mathura'# your API key will come hereapi = api_key_here# source contain json data from apisource = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q =' + city + '&appid =' + api).read()# converting JSON data to a dictionarylist_of_data = json.loads(source)# data for variable list_of_datadata = {"country_code": str(list_of_data['sys']['country']),"coordinate": str(list_of_data['coord']['lon']) + ' ' + str(list_of_data['coord']['lat']),"temp": str(list_of_data['main']['temp']) + 'k',"pressure": str(list_of_data['main']['pressure']),"humidity": str(list_of_data['main']['humidity']),}print(data)return render_template('index.html', data = data)if __name__ == '__main__':app.run(debug = True)

导航至模板/index.html 并编辑:链接至索引文件。

现在,您可以运行服务器来查看天气应用程序–

 python weather.py 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词