1. 程式人生 > >Python-Django 檢視層

Python-Django 檢視層

1 request物件

method:請求方式
GET:get請求的引數(post請求,也可以攜帶引數)
POST:post請求的引數(本質是從bdoy中取出來,放到裡面了)
COOKIES--->後面講
META:字典(放著好多東西,前端傳過來的,一定能從其中拿出來)
body:post提交的資料
path:請求的路徑,不帶引數
request.get_full_path() 請求路徑,帶引數
session---後面講
user---後面講
FILES
encoding:編碼格式

2 HttpResponse物件

-三件套
-JsonResponse:往前端返回json格式資料(沒有它,我可以自己寫)
-轉列表格式:指定safe=False
-中文字元問題:json_dumps_params={'ensure_ascii':False}

3 JsonResponse

# JsonResponse
url(r'^json$', app01_views.JasonRes),
def JasonRes(request):
dic={'id':1,'name':'lll六六六','publish':'laonanhai','publish_date':'2019-01-9','author':'dj'}
# import json
# return HttpResponse(json.dumps(dic,ensure_ascii=False))
return JsonResponse(dic,safe=False,json_dumps_params={'ensure_ascii':False})

(開車內容) wsgiref,uwsgi,---都遵循wsgi協議

-遵循一個協議wsgi(Web Server Gateway Interface web服務閘道器介面)

4 CBV(基於類的檢視)和FBV(基於函式的檢視)

-cbv:一個路由寫一個類
-先定義一個類:繼承自View
from django.views import View
class MyClass(View):
# 當前端發get請求,會響應到這個函式
def get(self, request):
return render(request,'index.html')
# 當前端發post請求,會響應到這個函式
def post(self,request):
print(request.POST.get('name'))
return HttpResponse('cbv--post')
-在路由層:
re_path('^myclass/$',views.MyClass.as_view()),

# CBV
url(r'^myclass/$', app01_views.Myclass.as_view()),
from django.views import View
class Myclass(View):
def get(self,request):
return render(request,'index.html')

def post(self,request):
print(request.POST.get('name'),request.POST.get('pwd'))
return HttpResponse('CBV--POST')

5 檔案上傳

-form表單預設提交的編碼方式是enctype="application/x-www-form-urlencoded"
-前端:如果要form表單上傳檔案,必須指定編碼方式為:multipart/form-data
-後端:
file=request.FILES.get('myfile')
with open(file.name,'wb') as f:
for line in file:
f.write(line)

# FILES
url(r'^file', app01_views.file_upload),
def file_upload(request):
if request.method=='GET':
return render(request,'file_upload.html')
else:
print(request.POST)
print(request.FILES)
from django.core.files.uploadedfile import InMemoryUploadedFile
file1=request.FILES.get('myfile1')
print(type(file1))
file2=request.FILES.get('myfile2')
import os,time
name=str(time.strftime("%Y-%m-%d"))+file1.name
print(name)
path=os.path.join('media',name)
print(path)
with open(path,'wb') as f:
for line in file1:
f.write(line)
# with open(file2.name,'wb') as f:
# for line in file2:
# f.write(line)
return HttpResponse('上傳成功!')

<body>
<form action="" method="post" enctype="multipart/form-data">
{#<form action="" method="post" enctype="application/x-www-form-urlencoded">#}
<p>使用者名稱 <input type="text" name="name"></p>
<input type="file" name="myfile1">
{# <input type="file" name="myfile2">#}
<input type="submit" name="submit">
</form>
</body>


6 前端提交資料編碼格式:

-multipart/form-data(上傳檔案)
-application/x-www-form-urlencoded(預設編碼)

7 圖書管理系統表分析:

圖書管理系統
-表:
book表
author表
publish表

-一對一:一對多的關係一旦確立,關聯欄位寫在哪都可以
-一對多:一對多的關係一旦確立,關聯關係寫在多的一方
-多對多:多對多的關係,必須建立第三張表(中間表)