創建項目
創建工程項目如下所示:
設置文件settings.py
中的設置主要有兩個
1.注冊app
2.設置templates的路徑
前面的文章已經介紹過多次如何設置了,此處不再做詳細贅述。
接口api為:http://api.map.baidu.com/telematics/v3/weather?location=%E9%83%91%E5%B7%9E&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?
主要流程分以下幾步:
1.從接口獲取數據,經過urls.py文件傳送給index.html文件。
2.在index.html文件中做界面處理,使界面美觀好看。
3.添加查詢功能。
獲取數據和傳送數據在前面的電影查詢網站已經講過 ,這里著重說一下添加查詢功能的原理。
本次仍然是用form表單實現查詢功能,form表單的method不做設置的話會默認get請求,當我們第一次傳送數據到界面之后,
可以在form表單設置個請求方式,然后在下次請求數據的時候,添加一個判斷,判斷的時候把form表單輸入的城市信息更改
為下次請求的時候的城市信息即可。
下附代碼:
視圖文件views.py
文件中的代碼如下:
from django.shortcuts import renderimport requests# Create your views here.def index(request): if request.method == 'POST': city = request.POST['city'] url = 'http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(city) else: url = 'http://api.map.baidu.com/telematics/v3/weather?location=%E9%83%91%E5%B7%9E&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?' json_data = requests.get(url).json() weather = json_data['results'][0]['weather_data'] today_weather = weather[0] t_weather = weather[1] tt_weather = weather[2] ttt_weather =weather[3] city = json_data['results'][0]['currentCity'] context = { 'today':today_weather, 'city':city, 'list':[t_weather,tt_weather,ttt_weather] } return render(request,'index.html',context)
urls.py
文件中的代碼如下:
from django.contrib import adminfrom django.urls import pathfrom myApp import viewsurlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index), path('select/',views.index),]
index.html
界面文件代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>{{city}}天氣信息</title> <style> html,body{ height:100%; margin:0; color: white; text-align: center; } body{ /*漸變色*/ background: linear-gradient(#1078c7,#7196b4); } form{ text-align: center; } main img{ width: 80px; } h1{ margin:5px; } footer{ display: flex; } section{ flex-grow: 1; border-right:1px solid greenyellow; } section:nth-child(3){ border:none; } </style></head><body> <form action="/select/" method="POST"> {% csrf_token %} <input name="city" type="text" placeholder="請輸入城市"> <button type="submit">查詢</button> </form> <main> <h2>實時天氣</h2> <img src="{{today.dayPictureUrl}}" alt=""> <h1>{{today.temperature}}</h1> <div> {{today.weather}}<br> {{today.wind}}<br> {{today.date}}<br> </div> </main> <footer> {% for weather in list %} <section> <h4>{{weather.date}}</h4> <img src="{{weather.dayPictureUrl}}" alt=""> <div> {{weather.temperature}}<br> {{weather.weather}}<br> {{weather.wind}}<br> </div> </section> {% endfor %} </footer></body></html>
新聞熱點
疑難解答