首页 > 编程语言 >小白学Python - 使用 Django 的天气应用程序

小白学Python - 使用 Django 的天气应用程序

时间:2023-10-21 16:08:08浏览次数:32  
标签:Python request list Django api 小白学 import main data

使用 Django 的天气应用程序

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

基本设置

cd weather

启动服务器

python manage.py runserver

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

ctrl-c

执行 :

python manage.py startapp main

通过执行以下操作转到 main/ 文件夹:

cd main

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

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

小白学Python - 使用 Django 的天气应用程序 _应用程序

现在添加主应用程序settings.py

小白学Python - 使用 Django 的天气应用程序 _应用程序_02

在天气中编辑

from django.contrib import admin 
from django.urls import path, include 


urlpatterns = [ 
	path('admin/', admin.site.urls), 
	path('', include('main.urls')), 
] 

在 main 中编辑

from django.urls import path 
from . import views 

urlpatterns = [ 
		path('', views.index), 
] 

在main中编辑views.py:

from django.shortcuts import render 
# import json to load json data to python dictionary 
import json 
# urllib.request to make a request to api 
import urllib.request 


def index(request): 
	if request.method == 'POST': 
		city = request.POST['city'] 
		''' api key might be expired use your own api_key 
			place api_key in place of appid ="your_api_key_here " '''

		# source contain JSON data from API 

		source = urllib.request.urlopen( 
			'http://api.openweathermap.org/data/2.5/weather?q ='
					+ city + '&appid = your_api_key_here').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) 
	else: 
		data ={} 
	return render(request, "main/index.html", data) 

可以从: Weather API获取您自己的 API 密钥

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

进行迁移并迁移它:

python manage.py makemigrations
python manage.py migrate

现在让我们运行服务器来查看您的天气应用程序。

python manage.py runserver

小白学Python - 使用 Django 的天气应用程序 _html_03

标签:Python,request,list,Django,api,小白学,import,main,data
From: https://blog.51cto.com/demo007x/7967152

相关文章

  • 代码随想训练营第十天(Python)| 232.用栈实现队列 、 225. 用队列实现栈
    232.用栈实现队列classMyQueue:def__init__(self):self.stack_in=list()self.stack_out=list()defpush(self,x:int)->None:self.stack_in.append(x)defpop(self)->int:ifself.empty():......
  • python打包成exe
    python打包成exe前提:文件可成功运行,为了方便后续使用或者发送给他人使用pyinstaller-F-F:生成单个文件。缺点:文件启动慢-D:打包成一个目录目录处理打包后文件过大的问题:①win+R进入cmd/powershell②安装虚拟环境:pipinstallvirtualenvpipinstallvirtualenvwrapper-win③制作......
  • Python定时任务框架APScheduler
    Python定时任务框架APSchedulerPython定时任务框架APScheduler详解-CSDN博客python定时任务最强框架APScheduler详细教程-知乎(zhihu.com) 课程详情接口思路一:直接在之前写好的查询所有课程的视图类上,配置一个类即可classCourseView(GenericViewSet,CommonListModelM......
  • python画边界框bounding box
    边界框的坐标方向:pythonopencv画边界框程序:[程序摘自pythonOpenCV画boundingbox并标明数据类]importcv2importnumpyasnpclass_name="car"box_left_top=np.array([75,35])#bbox左上角坐标box_right_bottom=np.array([475,220])#bbox右下角坐标......
  • Python内置的正则库 re
    Python-正则表达式re模块正则表达式(regularexpression,regex)正则表达式模式(pattern)字符普通字符和元字符大多数字母和符号都会简单地匹配自身。例如,正则表达式 test 将会精确地匹配到 test 。(你可以启用不区分大小写模式,让这个正则也匹配 Test 或 TEST ,稍后会详......
  • python tarfile模块
    一、简介tarfile 模块提供了创建、打开、读取和写入tar文件的函数和类。以下是该模块中常用的一些函数和类:tarfile.open(name,mode='r',fileobj=None,**kwargs):打开一个tar文件,返回一个TarFile对象。TarFile.add(name,arcname=None,recursive=True,filter=None):......
  • Python打印动态进度条
    importtimedefmyprocess(percent):ifpercent>1:percent=1#打印对应的#号数量*"#"=>字符串#号效果strvar=int(percent*50)*"#"#\r将后面字符覆盖到行首进行打印%%=>%print("\r[%-50s]%d%%"%(s......
  • Python:Anaconda安装虚拟环境到指定路径
    anaconda 总是会把虚拟环境默认安装至C盘,但是C盘容量有限,所以目标将虚拟环境安装至其他盘。步骤如下:通过查阅anaconda的文档,发现是可以进行指定路径安装的。可以输入如下命令进行查看:condacreate--help安装虚拟环境到指定路径的命令如下:condacreate--prefix=F:\sofe......
  • Python使用GARCH,EGARCH,GJR-GARCH模型和蒙特卡洛模拟进行股价预测|附代码数据
    全文下载链接:http://tecdat.cn/?p=20678最近我们被客户要求撰写关于GARCH的研究报告,包括一些图形和统计输出。在本文中,预测股价已经受到了投资者,政府,企业和学者广泛的关注。然而,数据的非线性和非平稳性使得开发预测模型成为一项复杂而具有挑战性的任务在本文中,我将解释如何将 ......
  • celery包结构、celery延迟任务和定时任务、django中使用celery、接口缓存、双写一致性
    celery包结构project├──celery_task#celery包│├──__init__.py#包文件│├──celery.py#celery连接和配置相关文件,且名字必须叫celery.py│└──tasks.py#所有任务函数├──add_task.py#添加任务......