VIEW 視圖

 FBV    CBV

 Django中請求處理方式有兩種: FBV和CBVhtml

FBV: function base views    在試圖裏使用函數處理請求ajax

# url對應關係:url(r'^add_publisher/', views.add_publisher),
from django.views import View

def add_publisher(request):
    '''新增出版社數據'''
    if request.method == 'POST':
        # 獲取提交的數據(括號內爲input的name屬性值),沒有默認空字符串
        new_name = request.POST.get('new_name','').strip()
        # 設定輸入不能爲空
        if not new_name:
            return render(request,'add_publisher.html',{'err_msg':'輸入不能爲空','name':new_name})
        # 設定不能與數據庫現有數據重複
        obj_list =  models.Publisher.objects.filter(name=new_name)    # 在數據庫中查詢數據是否存在
        if obj_list:        # 數據重複
            return render(request, 'add_publisher.html', {'err_msg': '出版社名稱已存在', 'name': new_name})
        # orm往數據庫中寫入數據
        if new_name and not obj_list:
            models.Publisher.objects.create(name=new_name)
            return redirect('/publisher_list/')
    # 若是不是post請求,仍是返回本頁面
    return render(request,'add_publisher.html')
示例

 

CBV : class base views    在試圖裏使用類處理請求數據庫

# url對應關係:url(r'^add_publisher/', views.add_publisher.as_view()),
from django.views import View

class add_publisher(View):
    def get(self,request):
        '''get請求'''
        return render(request, 'add_publisher.html')
    def post(self,request):
        # 獲取提交的數據(括號內爲input的name屬性值),沒有默認空字符串
        new_name = request.POST.get('new_name', '').strip()
        # 設定輸入不能爲空
        if not new_name:
            return render(request, 'add_publisher.html', {'err_msg': '輸入不能爲空', 'name': new_name})
        # 設定不能與數據庫現有數據重複
        obj_list = models.Publisher.objects.filter(name=new_name)  # 在數據庫中查詢數據是否存在
        if obj_list:  # 數據重複
            return render(request, 'add_publisher.html', {'err_msg': '出版社名稱已存在', 'name': new_name})
        # orm往數據庫中寫入數據
        if new_name and not obj_list:
            models.Publisher.objects.create(name=new_name)
            return redirect('/publisher_list/')
示例

 

 as_view()流程

1.程序啓動的時候,執行as_view() 定義view函數並返回return self.dispatch(request, *args, **kwargs)django

  url(r'^add_publisher/', views.add_publisher.as_view()) 此時就至關於url(r'^add_publisher/', view)json

2.接收到請求的時候,執行view函數session

  1.實例化當前的類 將對象傳給selfapp

  2.self.request = requestide

  3.指定返回的self.dispatch方法:函數

    1.判斷請求方式是否容許post

      容許 ---- 經過反射拿到對應請求方式的方法 賦值給handler

      不容許 ---- 執行self.http_method_not_allowed 賦值給handler

    2.執行handler 獲得HttpResponse對象 返回

 給視圖加裝飾器

FBV自己就是函數,和普通的函數加裝飾器的方法同樣,沒有區別

給CBV加裝飾器

from django.utils.decorators import method_decorator

#裝飾器
def timer(func):
    def inner(*args,**kwargs):
        start = time.time()
        ret = func(*args,**kwargs)
        print('時間:{}'.format(time.time() - start))
        return ret
    return inner


# 1.加在方法上

@method_decorator(timer)
def get(self,request):
    '''get請求'''
    return render(request, 'add_publisher.html')


# 2.加在dispatch方法上
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):     # 將源碼中的dispatch方法從新定義,至關於給全部方法加上裝飾器
    ret = super().dispatch(request, *args, **kwargs)
    return ret
    
    
# 3.加在類上
@method_decorator(timer,name='post')
@method_decorator(timer,name='get')       # 在name中指定要加裝飾器的方法
class AddPublisher(View):
    def dispatch(self, request, *args, **kwargs):
        pass
    def get(self,request):
        pass
    def post(self,request):
        pass
    

@method_decorator(timer,name='dispatch')        # 或者直接指定dispatch方法,效果同方法2同樣,給全部方法加上裝飾器
    def dispatch(self, request, *args, **kwargs):
        pass
    def get(self,request):
        pass
    def post(self,request):
        pass
給CBV加裝飾器

 

method_decorator使不使用對於代碼的運行效果來講,沒有什麼不一樣

可是從參數角度來說:

不使用method_decorator,打印args的結果:

  (<app01.views.AddPublisher object at 0x03B465B0>, <WSGIRequest: GET '/add_publisher/'>)

使用method_decorator,打印args的結果:

  (<WSGIRequest: GET '/add_publisher/'>,)

request

當一個頁面被請求時,Django就會建立一個包含本次請求原信息的HttpRequest對象

Django會將這個對象自動傳遞給響應的視圖函數,通常視圖函數約定俗成地使用 request 參數承接這個對象

#  屬性
request.method        # 請求方法
request.GET           # URL上攜帶的參數
request.POST          # POST請求提交的數據
request.FILES         # 上傳的文件
request.path_info     # 路徑   不包含IP 端口 參數
request.body          # 請求體   請求數據 字節  get沒有請求體
request.META          # 請求頭的信息  所有大寫 HTTP_開頭
request.COOKIES    
request.session

#  方法
request.get_full_path()    # 路徑  不包含IP和端口 包含參數
request.is_ajax()          # 是不是ajax請求,布爾值
request.get_host()         # 獲取主機的IP和端口

 

上傳文件

1.from表單中規定編碼方式 enctype="multipart/form-data"

2.使用request.FILES方法獲取文件

3.寫入文件: 文件名.chunks 將文件分塊 循環寫入

from django.shortcuts import render

def upload(request):
    if request.method == 'POST':
        file = request.FILES.get('file')        # request.FILES獲取到字典,經過鍵取值
        with open(file.name,'wb') as f:         # file.name拿到文件名
            for chunk in file.chunks():
                f.write(chunk)
    return render(request,'upload.html')
# 文件會自動保存到與manage.py同一個路徑下
函數
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    文件 <input type="file"  name="s19">
    <button>上傳</button>
</form>
</body>
</html>
模板

 

response

HttpResponse('字符串') 返回字符串

render(request,'模板的文件名',{k1:v1}) 返回一個完整的HTML頁面

redirect(要跳轉的地址) 重定向 Location :地址

每一個視圖都須要實例化,填充和返回一個HttpResponse,render和redirect源碼中都包含HttpResponse

JsonResponse是HttpResponse的子類,專門用來生成JSON編碼的響應

默認只能傳遞字典類型,若是要傳遞非字典類型須要設置一下safe關鍵字參數

from django.http.response import JsonResponse
def json_data(request):
    data = {'name':'alex','age':18}
    # lst = [1,2,3,4,5]
    return JsonResponse(data)
    # return JsonResponse(lst,safe=False)          # 傳輸非字典類型
示例
相關文章
相關標籤/搜索