返回主目錄:Django框架html
FBV:基於函數的視圖 CBV:基於類的視圖
不管是FBV仍是CBV路由層都是路由對應視圖函數內存地址 CBV: # 路由層代碼 from app01 import views urlpatterns = [ # url(r'^mycls/',views.view) url(r'^mycls/',views.MyLogin.as_view()) ] # 視圖層代碼 from django.views import View from django.shortcuts import HttpResponse class MyLogin(View): def get(self,request): return HttpResponse('get') def post(self,request): return HttpResponse('post') 1> views.py裏面的MyLogin類中並無定義as_view()方法,在其繼承的父類中定義了as_view方法,且被@classonlymethod裝飾器裝飾,做爲類的函數; 2> 該方法下面包含了一個view閉包函數,返回定義的view函數的內存地址,回到urls,再執行返回的view這個方法; 3> 在view函數內部,實例化了一個自定義類的對象,返回這個對象的dispatch方法(該方法在View這個類內部,定義爲對象方法); 4> dispatch方法中,獲取了request方法的請求方式,判斷是否爲八種請求方式中的一種,是,則去執行自定義類中的相應請求的方法; 5> 執行的即是在自定義類中定義的get/post方法。
方式一: import json def index(request): res = {'name': '張三', 'password': 18} return HttpResponse(json.dumps(res)) 渲染到前端結果: # {"name": "\u5f20\u4e09", "password": 18} 方式二: from django.http import JsonResponse def index(request): res = {'name': '張三', 'password': 18} return JsonResponse(res,json_dumps_params={'ensure_ascii':False}) 渲染到前端結果: # {"name": "張三", "password": 18} print('path:',request.path) print('full_path:',request.get_full_path()) path: /upload_file/ full_path: /upload_file/?name=jason
前端須要注意的點: 1.method須要指定成post 2.enctype須要改成multipart/form-data格式 前端html: <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="my_file" > <input type="submit" value="提交"> </form> 後端暫時須要注意的是 1.配置文件中註釋掉csrfmiddleware中間件 2.經過request.FILES獲取用戶上傳的post文件數據 後端接收數據邏輯: file_obj = request.FILES.get('my_file') print(file_obj.name) with open(file_obj.name,'wb') as f: for line in file_obj.chunks(): f.write(line)
request.method:表示提交請求使用的HTTP方法。它老是大寫的。 request.GET:一個類字典對象,包含全部的HTTP的GET參數的信息。 request.POST:一個類字典對象,包含全部的HTTP的POST參數的信息。 request.FILES:一個類字典對象,包含全部上傳的文件。 request.path:一個字符串,表示請求的路徑(不含域名)。 request.get_full_path():一個字符串,表示請求的完整路徑。 request.body:一個字符串,表明請求報文的主體。