django的檔案上傳&JsonResponse的使用&資料庫的連線
1 request物件
method:請求方式
GET:get請求的引數(post請求,也可以攜帶引數)
POST:post請求的引數(本質是從bdoy中取出來,放到裡面了)
COOKIES:
META:字典(放著好多東西,前端傳過來的,一定能從其中拿出來)
body:post提交的資料
path:請求的路徑,不帶引數
request.get_full_path() 請求路徑,帶引數
session:
user:
FILES
encoding:編碼格式
is_ajax():
2 HttpResponse物件
-三件套
法一:
HttpResponse(json.dumps(dic,ensure_ascii=False))
法二:
From django.http import JsonResponse
-JsonResponse:往前端返回json格式資料(沒有它,我可以自己寫)
-轉列表格式:指定safe=False
-中文字元問題:json_dumps_params={'ensure_ascii':False}
3 wsgiref,uwsgi,---都遵循wsgi協議
Wsgiref自己寫程式碼時用,uwsgi上線用(可以解決高併發)
-遵循一個協議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()),
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)
6 前端提交資料編碼格式:
-multipart/form-data(上傳檔案)
-application/x-www-form-urlencoded(預設編碼)
7 圖書管理系統表分析:
圖書管理系統
-表:
book表
author表
publish表
-一對一:一對多的關係一旦確立,關聯欄位寫在哪都可以
-一對多:一對多的關係一旦確立,關聯關係寫在多的一方
-多對多:多對多的關係,必須建立第三張表(中間表)
8 models中寫的class時 的注意點
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
pub_date = models.DateField()
# max_digits:最長是5,decimal_places:小數點後兩位
price = models.DecimalField(max_digits=5, decimal_places=2)
# to='Publish',to_field='id':外來鍵關聯到publish表的id欄位
# to 哪個表的引號可以去掉,前提是這個表必須在前面定義,推薦加引號的(使用了ForeignKey,它會自動在publish後面加_id變成publish_id)
publish = models.ForeignKey(to='Publish', to_field='id',on_delete=models.CASCADE)
# 寫了這一句,相當於建立了第三章表(手動建立第三張表也可以,後面表),不會在資料庫建立authors欄位
authors = models.ManyToManyField(to='Author')
9 settings中的配置檔案(表格插入mysql)
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '0109',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root',
}