Python學習(六) 定義視圖以及頁面模板

來源:互聯網
上載者:User

標籤:

  請求解析一般都是通過請求的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學習(六) 定義視圖以及頁面模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.