在本教程中,我们将学习如何创建一个使用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

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

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

现在添加主应用settings.py

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

在天气中编辑 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教程之实现天气应用程序

原文地址:https://juejin.cn/post/7157347431863025672

相关文章: