CBV和FBV
-
-
CBV(class based view)
1. CBV的定义
# 增加出版社 CBV from django.views import View class AddPublisher(View): def get(self, request): pass def post(self, request): pass
2. CBV使用
url(r'^add_publisher/', views.AddPublisher.as_view()),
3. CBV的流程
views.AddPublisher.as_view() 程序加载的时候执行 ——》 view函数
-
self = AddPublisher()
-
self.request = request
-
执行self.dispatch方法
-
判断请求方式是否被允许
-
允许时,通过反射获取到AddPublisher中定义的get或者post方法 ——》handler
-
不允许时,self.http_method_not_allowed ——》handler
-
-
执行handler 拿到返回结果 Httpresponse对象
4. 给CBV加装饰器 method_decorator
from django.utils.decorators import method_decorator
加载到某个get 或者 post的方法上:
@method_decorator(timer) def get(self, request):
加在self.dispatch方法上:
@method_decorator(timer) def dispatch(self, request, *args, **kwargs):
加在类上:
@method_decorator(timer, name='post') @method_decorator(timer, name='get') class AddPublisher(View):
5. 区别
func: <function AddPublisher.dispatch at 0x00000163735176A8>args :<app01.views.AddPublisher object at 0x00000163735F7EF0> <WSGIRequest: GET '/add_publisher/'>
-
使用method_decorator
func:<function method_decorator.<locals>.dec.<locals>.wrapper.<locals>.bound_func at 0x0000019664B4A378>arsgs: <WSGIRequest: GET '/add_publisher/'>
简而言之:
不使用method_decorator的时候, 第二个参数是request
使用method_decorator的时候, 第一个参数是request
print(request.method) # GET 请求方式 print(request.GET) # get的请求数据 QueryDict{} print(request.POST) # post的请求数据 QueryDict{} print(request.FILES) # 上传文件时获取到的数据 print(request.path_info) # 路径信息 不包含IP和端口、参数
print(request.path) #获取请求路径信息
print(request.is_ajax()) #是否是ajax请求 print(request.get_host()) print(request.get_full_path()) # 路径信息 + 参数
文件上传
view.py
# 上传文件 def upload(request): if request.method == 'POST': # print(request.body) file = request.FILES.get('f1') with open(file.name, 'wb') as f: for chunk in file.chunks(): f.write(chunk) return HttpResponse('上传成功') return render(request, 'upload.html') import json from django.http import JsonResponse def json_test(request): data = {'name': 'alex', 'pwd': 'alexdsb'} ret = HttpResponse(json.dumps(data)) ret['Content-Type'] = 'application/json' ret['xxx'] = 'axxx' return ret # return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8 # return JsonResponse(data) # Content-Type: application/json
template
<!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="f1"> <button>上传</button> </form> </body> </html>
-
form表单的enctype = 'multipart/form-data'
-
request.FILES中获取文件对象
-
使用文件对象的chunks()
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