1.什么是視圖層
簡單來說,就是用來接收路由層傳來的請求,從而做出相應的回應回傳給瀏覽器
2.視圖層的格式與引數說明
2.1基本格式
from django.http import HttpResponse
def page_2003(request):
html = '<h1>第一個網頁</h1>'
return HttpResponse(html)
# 注意需要在主路由檔案中引入新創建的視圖函式
2.2帶有轉換器引數的視圖函式
def test(request, num):
html = '這是我的第%s個網頁' % num
return HttpResponse(html)
# 添加轉換器的視圖函式,request后面的引數num為path轉換器中的自定義名
2.3帶有正則運算式引數的視圖函式
同帶有轉換器引數的視圖函式
2.4重定向的視圖函式
from django.http import HttpResponse,HttpResponseRedirect
def test_request(request):--注意path函式里也要系結test_request這個路徑
return HttpResponseRedirect('page/2003/')--重定向到127.0.0.1:8000/page/2003這個頁面去
2.5判斷請求方法的視圖函式
def test_get_post(request):
if request.method == 'GET':
pass
elif request.method == 'POST':
pass
2.6加載模板層的視圖函式
使用render()直接加載并相應模板語法:
?from django.shortcuts import render
?def test_html(request):
? return render(request, '模板檔案名', 字典資料)
注意視圖層的所有變數可以用local()方法全部自動整合成字典傳到render的最后一個引數里
2.7回傳JsonResponse物件的視圖函式
json格式的資料的作用:
前后端資料互動需要用到json作為過渡,實作跨語言傳輸資料,
格式:
from django.http import JsonResponse
def ab_json(request):
user_dict={'username':'json,我好喜歡','password':'1243'}
return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
# 字典傳入時需要設定json_dumps_params格式化字串,不然字典里的中文會報錯
list = [111,22,33,44]
return JsonResponse(list,safe=False)
# 串列傳入序列化時需要設定safe為false ,不然會報錯
2.8視圖層的FBV和CBV格式
視圖函式既可以是函式(FBV)也可以是類(CBV)
1.FBV
def index(request):
return HttpResponse('index')
2.CBV
# CBV路由
pathr'^login/',views.MyLogin.as_view())
# CBV視圖函式
from django.views import View
class MyLogin(View):
def get(self,request):
return render(request,'form.html')
def post(self,request):
return HttpResponse('post方法')
"""
FBV和CBV各有千秋
CBV特點
能夠直接根據請求方式的不同直接匹配到對應的方法執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/505472.html
標籤:其他
上一篇:延宕執行,妙用無窮,Go lang1.18入門精煉教程,由白丁入鴻儒,Golang中defer關鍵字延遲呼叫機制使用EP17
