您现在的位置是:首页 > 编程语言学习 > 其他编程语言 > 文章正文 其他编程语言

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

2022-10-24 10:30:18 其他编程语言

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

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

基本设置

将目录更改为天气

  1. cd weather 

启动服务器

  1. python manage.py runserver 

要检查服务器是否正在运行,请转到 Web 浏览器并输入为 URL。现在,您可以通过按以下命令停止服务器http://127.0.0.1:8000/

ctrl-c

实现

  1. python manage.py startapp main 

转到主/文件夹通过做:

  1. cd main  

并创建一个包含文件的文件夹:templates/main/index.htmlindex.html

使用文本编辑器打开项目文件夹。目录结构应如下所示:

现在添加主应用settings.py

在天气中编辑 urls.py文件:

  1. from django.contrib import admin 
  2. from django.urls import path, include 
  3.  
  4.  
  5. urlpatterns = [ 
  6.     path('admin/', admin.site.urls), 
  7.     path('', include('main.urls')), 

在主文件中编辑 urls.py文件:

  1. from django.urls import path 
  2. from . import views 
  3.  
  4. urlpatterns = [ 
  5.         path('', views.index), 

在`主文件中编辑 views.py :

  1. from django.shortcuts import render 
  2. # 导入json以将json数据加载到python字典 
  3. import json 
  4. # urllib.request 向api发出请求 
  5. import urllib.request 
  6.  
  7.  
  8. def index(request): 
  9.     if request.method == 'POST'
  10.         city = request.POST['city'
  11.         ''' api密钥可能已过期,请使用您自己的api密钥 
  12. 将api_key替换为appid=“your_api_key_here” ''
  13.  
  14.         # 包含来自API的JSON数据 
  15.  
  16.         source = urllib.request.urlopen( 
  17.             'http://api.openweathermap.org/data/2.5/weather?q =' 
  18.                     + city + '&appid = your_api_key_here').read() 
  19.  
  20.         # 将JSON数据转换为字典 
  21.         list_of_data = json.loads(source) 
  22.  
  23.         # 变量list_of_data的数据 
  24.         data = { 
  25.             "country_code": str(list_of_data['sys']['country']), 
  26.             "coordinate": str(list_of_data['coord']['lon']) + ' ' 
  27.                         + str(list_of_data['coord']['lat']), 
  28.             "temp": str(list_of_data['main']['temp']) + 'k'
  29.             "pressure": str(list_of_data['main']['pressure']), 
  30.             "humidity": str(list_of_data['main']['humidity']), 
  31.         } 
  32.         print(data) 
  33.     else
  34.         data ={} 
  35.     return render(request, "main/index.html", data) 

您可以从中获取自己的 API 密钥:天气 API

导航并编辑它:链接到索引.html文件templates/main/index.html

进行迁移并迁移:

  1. python manage.py makemigrations 
  2. python manage.py migrate 

现在,让我们运行服务器以查看天气应用。


  1. python manage.py runserver 

站点信息