一 CBV, FBV
cbv: 基於類的視圖,業務邏輯 直接用函數處理邏輯業務( class based view)
fbv: 基於函數的視圖,業務邏輯 用類的概念處理邏輯業務(function based view)
二.
from django.views import View
class AddPublisher(View):
def get(self, request):
pass
def post(self, request):
pass
tip: 繼承views文件中的View,
重寫pot, post方法, 修改自己需要處理的業務邏輯
使用入口:
url(r'add_publisher' , views.AddPublisher.as_view())
這個函數在Django程序開啟后立即執行,as_view的方法,
返回一個view函數, 這個函數攜帶着一些屬性和方法,(暫時不做細究)
函數在請求進來之后執行,並且實例化,匹配url請求方式, 依照請求方式
執行對應的方法,這里利用了反射,將請求方式GET, POST, PUT..8個方法放置在一個列表中,如果請求方式不在列表中,也會返回一個方法給handler並且執行
三 .給CBV加裝飾器:
導入模塊
import time
from django.utils.decorators import method_decorator
def timer(func)
def inner(*arge, **kwargs)
print(time.tieme()
ret = func()
print(time.time())
return ret
return inner
1, 加載裝飾器到get/post的方法上面: # 放置在不同的請求方式上面,
@method_decorator(timer)
def post(self, request)
2. 加載到self.dispatch方法上面: (所有請求的執行完畢都生效)
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs): # 這個方法是匹配請求方式的: GET or POST or...
...
3. 加載到類上面 : 注意這里不會有順序問題,裝飾器只會給name對應的方法加裝飾器,不重疊,不是多層嵌套
@method_decorator(timer, name='post')
@method_decorator(timer, name='get')
class AddPublisher(View):
tip: 區別 : 傳參數會有區別, 一個類方法攜帶了self, 函數不攜帶self ,傳request的時候注意下
1. 不使用method_decorator
func: <function AddPublisher.dispatch at 0x00000163735176A8>
args :<app01.views.AddPublisher object at 0x00000163735F7EF0> <WSGIRequest: GET '/add_publisher/'>
2. 使用method_decorator
func:<function method_decorator.<locals>._dec.<locals>._wrapper.<locals>.bound_func at 0x0000019664B4A378>
arsgs: <WSGIRequest: GET '/add_publisher/'>
四。 HttpResponse中 request對象:請求進來后生成的對象 : 這個對象包含請求中所有的信息
屬性:request.path_info: 用戶訪問的 url, 不包括域名參數等
request.get_host(): 主機信息
request.get_full_path(): 路徑信息 + 參數
request.GET : 對象{} [] get()
request.POST : 對象{} [] get()
request.FILES: 發送上傳文件的請求
上傳文件注意事項: 1. form表單的enctype='multipart/form-data'
2. request.FILES中獲取文件對象 (文件緩存着)
3. 使用文件對象的chunks()
HttpResponse 子類JsonResponse
from django.http import JsonResponse
JsonResponse: 生成JSON編碼的響應
response = JsonResponse({'foo': 'bar'})
print(response.content)
b'{"foo": "bar"}'
JsonResponse([1,2,3], safe=false) : 設置參數, 。
from django.http import JsonResponse
def json_test(request):
data = {'name': 'alex', 'pwd': 'alexdsb'}
return JsonResponse(data) # Content-Type: application/json
# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8 # 設置請求頭文本類型