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 命令

py 复制代码
touch weather.py 

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

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

py 复制代码
 mkdir templates && cd templates && touch index.html 

项目文件夹看起来像:

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

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.request

app = Flask(__name__)

@app.route('/', methods =['POST', 'GET'])
def weather():
    if request.method == 'POST':
        city = request.form['city']
    else:
        # for default name mathura
        city = 'mathura'

    # your API key will come here
    api = api_key_here

    # source contain json data from api
    source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q =' + city + '&appid =' + api).read()

    # converting JSON data to a dictionary
    list_of_data = json.loads(source)

    # data for variable list_of_data
    data = {
        "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 并编辑:链接至索引文件

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

py 复制代码
 python weather.py 
相关推荐
二川bro12 小时前
第41节:第三阶段总结:打造一个AR家具摆放应用
后端·restful
aiopencode12 小时前
苹果应用商店上架全流程 从证书体系到 IPA 上传的跨平台方法
后端
百***860512 小时前
Spring BOOT 启动参数
java·spring boot·后端
wei_shuo12 小时前
基于Linux平台的openGauss一主两备高可用集群部署与运维实践研究
后端
by__csdn12 小时前
微服务与单体那些事儿
java·后端·微服务·云原生·架构
天草二十六_简村人13 小时前
dify中级入门示例--使用知识库搭建智能客服机器人
后端·ai·云原生·ai编程
MediaTea13 小时前
Python 第三方库:cv2(OpenCV 图像处理与计算机视觉库)
开发语言·图像处理·python·opencv·计算机视觉
江塘13 小时前
机器学习-决策树多种生成方法讲解及实战代码讲解(C++/Python实现)
c++·python·决策树·机器学习
多彩电脑13 小时前
死循环逻辑检测
数据结构·python·算法·动态规划
YongCheng_Liang13 小时前
Python 基础核心模块全解析:从入门到实践的知识框架
python