[Python] Python Django教程之实现天气应用程序

2318 0
黑夜隐士 2022-11-9 17:55:59 | 显示全部楼层 |阅读模式
目录

    基本设置实现

在本教程中,我们将学习如何创建一个使用Django作为后端的天气应用程序。Django提供了一个基于Python Web框架的Web框架,允许快速开发和干净,务实的设计。

基本设置

将目录更改为天气
cd weather
启动服务器
python manage.py runserver
要检查服务器是否正在运行,请转到 Web 浏览器并输入为 URL。现在,您可以通过按以下命令停止服务器http://127.0.0.1:8000/
ctrl-c

实现

python manage.py startapp main
转到主/文件夹通过做:
cd main
并创建一个包含文件的文件夹:templates/main/index.htmlindex.html
使用文本编辑器打开项目文件夹。目录结构应如下所示:


现在添加主应用settings.py


在天气中编辑 urls.py 文件:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('main.urls')),
]
在主文件中编辑 urls.py 文件:
from django.urls import path
from . import views

urlpatterns = [
                path('', views.index),
]
在`主文件中编辑 views.py :
from django.shortcuts import render
# 导入json以将json数据加载到python字典
import json
# urllib.request 向api发出请求
import urllib.request

def index(request):
        if request.method == 'POST':
                city = request.POST['city']
                ''' api密钥可能已过期,请使用您自己的api密钥
                    将api_key替换为appid=“your_api_key_here” '''

                # 包含来自API的JSON数据

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

                # 将JSON数据转换为字典
                list_of_data = json.loads(source)

                # 变量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)
        else:
                data ={}
        return render(request, "main/index.html", data)
您可以从中获取自己的 API 密钥: 天气 API
导航并编辑它:链接到索引.html文件templates/main/index.html
进行迁移并迁移:
python manage.py makemigrations
python manage.py migrate
现在,让我们运行服务器以查看天气应用。
python manage.py runserver


到此这篇关于Python Django教程之实现天气应用程序的文章就介绍到这了,更多相关Python Django天气应用程序内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行