標籤:
請求解析一般都是通過請求的request擷取一定參數,然後根據參數做一定商務邏輯判斷,這其中可能包括查詢資料庫,然後將需要返回的資料封裝成一個HttpResponse返回。
代碼如下:
這是一個簡單的處理請求的函數,對應之前url映射的 url(r‘^articles/([0-9]{4})/$‘, views.year_archive),django會將url中用()包起來的內容作為變數傳給函數,此處year_archive中的year變數就是([0-9]{4})代表的值。
Article.objects.filter(pub_date__year=year)過濾出發布日期是year的資料。注意pub_date__year,資料庫表中只有pub_date欄位,pub_date__year代表值取年。
所以可以認為這是django預設提供的一種介面查詢方式。
然後將返回的list列表和year再組裝成一個字典資料。
最後調用django提供的函數render返回。render完成的事情其實就是選擇一個模板,建立一個Context對象,然後將這些資料放到建立的一個HttpResponse中去。
mysite/news/views.pyfrom django.shortcuts import renderfrom .models import Articledef year_archive(request, year): a_list = Article.objects.filter(pub_date__year=year) context = {‘year‘: year, ‘article_list‘: a_list} return render(request, ‘news/year_archive.html‘, context)
上面的代碼其實是對以下資料進行了封裝,render中封裝了以下代碼的作用。
from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request): now = datetime.datetime.now() # Simple way of using templates from the filesystem. # This is BAD because it doesn‘t account for missing files! fp = open(‘/home/djangouser/templates/mytemplate.html‘) t = Template(fp.read()) fp.close() html = t.render(Context({‘current_date‘: now})) return HttpResponse(html)
Python學習(六) 定義視圖以及頁面模板