簡單的django框架應用及小專案一
阿新 • • 發佈:2018-11-10
一、用django框架獲取全國天氣
在我們開始做專案的步驟大概分為四個步驟:
準備階段
1.首先,我們在桌面建一個新的資料夾,然後在在這個資料夾裡新建專案(在終端裡程式碼建立),新建App,操作過程如下圖所示:
2. -建好專案與App後,我們還需要引入js,還要建立一個模板頁,最終成功的頁面如下:
3.配置階段
1.在setting裡面,需要修改三處
2.在url裡面
3.views裡面
4.獲取資訊並做一下簡單處理
from django.shortcuts import render import 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)
5.最後在templates模板裡面的index裡面進行配置
<!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; margin-top:100px; } section{ flex-grow:1; border-right:1px solid greenyellow; } section:last-child { 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>
5.最後是展現頁面