日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python?Django教程之實(shí)現(xiàn)天氣應(yīng)用程序_python

作者:海擁 ? 更新時(shí)間: 2022-11-30 編程語(yǔ)言

在本教程中,我們將學(xué)習(xí)如何創(chuàng)建一個(gè)使用Django作為后端的天氣應(yīng)用程序。Django提供了一個(gè)基于Python Web框架的Web框架,允許快速開(kāi)發(fā)和干凈,務(wù)實(shí)的設(shè)計(jì)。

基本設(shè)置

將目錄更改為天氣

cd weather

啟動(dòng)服務(wù)器

python manage.py runserver

要檢查服務(wù)器是否正在運(yùn)行,請(qǐng)轉(zhuǎn)到 Web 瀏覽器并輸入為 URL?,F(xiàn)在,您可以通過(guò)按以下命令停止服務(wù)器http://127.0.0.1:8000/

ctrl-c

實(shí)現(xiàn)

 python manage.py startapp main

轉(zhuǎn)到主/文件夾通過(guò)做:

cd main 

并創(chuàng)建一個(gè)包含文件的文件夾:templates/main/index.htmlindex.html

使用文本編輯器打開(kāi)項(xiàng)目文件夾。目錄結(jié)構(gòu)應(yīng)如下所示:

現(xiàn)在添加主應(yīng)用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
# 導(dǎo)入json以將json數(shù)據(jù)加載到python字典
import json
# urllib.request 向api發(fā)出請(qǐng)求
import urllib.request


def index(request):
	if request.method == 'POST':
		city = request.POST['city']
		''' api密鑰可能已過(guò)期,請(qǐng)使用您自己的api密鑰
                    將api_key替換為appid=“your_api_key_here” '''

		# 包含來(lái)自API的JSON數(shù)據(jù)

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

		# 將JSON數(shù)據(jù)轉(zhuǎn)換為字典
		list_of_data = json.loads(source)

		# 變量list_of_data的數(shù)據(jù)
		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

導(dǎo)航并編輯它:鏈接到索引.html文件templates/main/index.html

進(jìn)行遷移并遷移:

python manage.py makemigrations
python manage.py migrate

現(xiàn)在,讓我們運(yùn)行服務(wù)器以查看天氣應(yīng)用。

python manage.py runserver

原文鏈接:https://juejin.cn/post/7157347431863025672

欄目分類(lèi)
最近更新