13.Django之view初探視圖函數(一)

1、什麼是視圖函數?
Django框架中的視圖函數其實就是個普通的python函數,這個函數能夠接收web請求,而且返回web響應。
視圖函數響應給客戶端瀏覽器的內容,能夠是一個html文檔,還能夠是一個重定向,還能夠是一張圖片,還能夠是一個重定向......
不管視圖函數中包含什麼樣的邏輯,都須要返回web響應。
通常狀況下,咱們喜歡把視圖函數放在views.py這個文件中。html

2、初識視圖函數的執行流程與結構。
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from django.urls import reverse
import datetimepython

def show_datetime(request):
now = datetime.datetime.now()
html = "< html >< body >*It is now %s.< /body >< /html >" % now
print(request)
return HttpResponse(html)web

(1)首先,咱們從 django.http模塊導入了HttpResponse類,以及Python的datetime模塊。
(2)接着,咱們定義了show_datetime函數。它是一個視圖函數。每一個視圖函數都應接收HttpRequest對象做爲第一個參數,通常叫作request。
(3)最終,這個視圖函數會返回出一個HttpResponse(響應)對象。(每一個視圖函數都要返回一個HttpResponse對象)django

(也就是說,每一個視圖函數至少要接收一個參數,接收的這個參數就是HttpRequest【http請求對象】,另外,每一個視圖函數也要返回一個對象,這個對象就是 HttpResponse【http響應對象】 )瀏覽器

http請求對象(HttpRequest)與http響應對象:HttpResponse這兩個對象的所在位置是django.http。服務器

3、view視圖函數中經常使用的快捷函數。框架

一、 render函數。
結合django模板,返回一個通過django模板語言渲染的HttpResponse 對象。
render的經常使用參數以下:
格式 render(request, template_name[, context])ide

request:render函數要傳的第一個參數就是用來生成這個響應的請求對象。
template_name :返回給瀏覽器的模板名稱,這個名稱是字符串格式。(這個參數是可選的。)
context:添加到模板上下文的一個字典。默認是一個空字典。若是字典中的某個值是可調用的,視圖將在渲染模板以前調用它。(說的通俗一點,就是給模板傳遞python變量或者指定的值,替換掉指定的字符串。)函數

content_type:生成的文檔要使用的MIME類型。默認爲DEFAULT_CONTENT_TYPE 設置的值。post

status:用來指定http的響應的狀態碼。默認爲200。

  1. redirect函數。
    用於跳轉到指定的url,這個url必須是django的url路由系統中定義好的url。
    示例:
    def auth_user(request):
    if request.method == 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')
    print(username,password)
    print(request.POST)
    if username == "admin" and password == "123456":
    return redirect('/test/admin/') # 當上面這個if判斷執行成功後,自動跳轉到/test/admin/這個url。
    return render(request,'login.html')

4、獲取httprequest內容的方法(獲取請求體內容)。
1.獲取當前請求類型:
request.method
例如說,如今須要判斷當前請求是否爲post類型:
if request.method == 'POST':

2.獲取get請求或者post請求的內容。
若是須要獲取POST請求的全部內容,可使用request.POST這個方法,使用了request.POST以後,會將post請求的全部內容以QueryDict這種類型返回,這個數據類型和python內置的字典特別相似,若是須要取出post請求中的某個值,可使用request.POST.get('key')方法,取出QueryDict這個字典中指定的值。
示例:
def auth_user(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
print(username,password)
print(request.POST)
if username == "admin" and password == "123456":
return redirect('/test/admin/')
return render(request,'login.html')

若是須要獲取客戶端瀏覽器提交的GET請求中的值,須要使用http請求的 request.GET方法,獲取GET請求的值沒什麼好須要特殊介紹的了,用法和request.POST同樣,也會返回一個QueryDict字典,要取出字典中的某個值,就使用get()方法。

3。獲取form表單中checkbox中全部的值。
當須要獲取form表單中的checkbox勾選框中全部的值時,就不能在使用.get方法了!
這一點須要特別注意!
當須要接收checkbox中的值,若是使用以前的request.POST.get()方法,若是使用checkbox多選框,那麼只會接收到checkbox的第一個值!其他的值沒法接收!!
這個時候就須要使用request.POST.getlist()方法!
假如說,如今須要得到form表單中,同一個name屬性中的多個值,或者說是QueryDict字典中同一個key裏面的多個value,這個時候就須要使用request.POST.getlist()方法!。
當使用了request.POST.getlist()方法後,同一個key中的多個值,會以列表的方式返回。
下面是個例子:
HTML部分:
< body >
< form action="/test/login2/" method="post" >

< p >
    選擇1:<input type="checkbox" name="c1" value="1">
    選擇2:<input type="checkbox" name="c1" value="2">
    選擇3:<input type="checkbox" name="c1" value='3'>
</p>
<input type="submit" value="提交">

< /form>
</ body>

view視圖函數部分:
def test_check(request):
if request.method == 'POST':
t_check = request.POST.getlist('c1') #獲取key爲c1的全部值。
print(request.POST)
print(t_check)
return render(request,'login.html')

這時,咱們打開瀏覽器,選中3個checkbox 而後提交,這時t_check這時獲取到的值將會是一個列表['1', '2', '3']。

4.經過form表單實現上傳文件。
django接收form表單傳過來的文件,則須要request.FILES方法。
下面是文件上傳功能的示例:
【1】html文檔:
< body>
< form enctype="multipart/form-data" method="post">
< input type="file" name="up_load_file"/>
< input type="submit" value="上傳" >
< /form >
< /body >

注意!!:在製做上傳文件的form表單時,必定要注意添加enctype="multipart/form-data"這個屬性!!不然會致使文件沒法上傳!!這個屬性的做用就是用來設置,form表單提交給服務器的媒體類型!!

【2】view視圖:
def upload_file(request):
if request.method == 'POST':
upfile = request.FILES.get('up_load_file')
write_file = open(upfile.name,mode='wb')
for item in upfile.chunks(): #!chunks生成迭代器對象。
write_file.write(item)
write_file.close()
return render(request,'upload.html')

#!注意!!!!!當equest.FILES.get接收到了form表單傳送過來的文件對象時,執行這個文件對象的chunks方法,就會生成一個迭代器對象,只要循環這個迭代器對象,就能夠獲取到文件中的內容。

5、經過另外一種方式建立view視圖(經過類的方式建立視圖)。
下面是經過類(class)的方式建立視圖函數的方法。

經過類建立的view視圖,建立方法以下:
from django.views import View
class Test(View):
def get(self,request):
print('當瀏覽器發起get請求時執行我!')
def post(self,request):
print('當瀏覽器發起post請求時執行我!')

那麼這個view視圖的類如何在url路由中調用呢?
urlpatterns=[
url(r'^datetime/',views.show_datetime),
url(r'^login/',views.auth_user),
url(r'^admin/',views.admin),
url(r'^req/',views.http_req),
url(r'^upload/',views.upload_file),
url(r'^home/',views.Test.as_view()), #!!!注意看這裏!!!

]

相關文章
相關標籤/搜索