使用 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
使用文本编辑器打开项目文件夹。目录结构应如下所示:
现在添加主应用程序settings.py
在天气中编辑
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,request,list,Django,api,小白学,import,main,data
From: https://blog.51cto.com/demo007x/7967152