Views
視圖views 用于處理應用的具體邏輯,也就是MTV里的V了。
假設我有一個blog,且要在article 的app 下,我要對views.py 進行代碼的編寫,我先要思考我的article 需要哪些功能,之后再考慮如何實現(xiàn),簡單的文章展示一般需要翻頁,文章展示這2個功能,那就根據(jù)這3個功能先做吧.
常見的view的架構還是基于function-based-view的,相比之下比較簡單,但當業(yè)務邏輯多了,且代碼復用的情況也同時增多的情況下,我覺得class-based-view 會比較適合,畢竟python是一門面向?qū)ο蟮恼Z言么,這個之后再說,先用函數(shù)方式實現(xiàn)一點功能吧。
翻頁功能,django 有個組件叫做pagination ,非常適合干這個事情,但是我叛逆,不用,于是自己寫吧,同樣以庫的形式寫在libs 下面:
#! /usr/bin/python
#-*- coding: utf-8 -*-
from db_conn import DB_Conn
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
def turn_page(request,sqla,sqlb):
global remainpost
dbconn,dbcursor = DB_Conn()
dbcursor.execute(sqla)
allcounts = dbcursor.fetchall()[0][0]
per_page = 5
allpage = allcounts / per_page
remainpost = allcounts % per_page
if remainpost > 0:
allpage += 1
try:
curpage = int(request.GET.get('curpage', '1'))
pagetype = str(request.GET.get('pagetype', ''))
except ValueError:
curpage=1
allpage=1
pagetype=''
if pagetype=="next":
curpage += 1
elif pagetype=="last":
curpage -=1
start = (curpage - 1) * per_page
lim_sql = sqlb + " limit " + str(start) + "," + str(per_page)
dbcursor.execute(lim_sql)
post = dbcursor.fetchall()
return (allpage,post,curpage)
大致意思就是先計算出總量,然后根據(jù)每頁多少個標題算出需要多少頁,然后根據(jù)url 傳值來判斷是下一頁還是上一頁。
然后在views 中調(diào)用這個庫:
#-*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from libs.db_conn import DB_Conn
from libs.pageturn import turn_page
from django.template import RequestContext
# Create your views here.
def article_home(request):
dbconn,dbcursor = DB_Conn()
sqla = "select count(*) from blog_article"
sqlb = "select * from blog_article"
allpage,post,curpage = turn_page(request,sqla,sqlb)
return render_to_response('index.html',{'tag':tag,'allpage':allpage,'post':post,'curpage':curpage},context_instance=RequestContext(request))
然后在APP目錄下建立templates ,創(chuàng)建對應的index.html,(其實我覺得應該是先建立templates 模版,在根據(jù)模版的需要搞視圖= = 網(wǎng)上教程既然都是先視圖,那就先弄視圖吧。)