1. 程式人生 > >django的文件上傳&JsonResponse的使用&數據庫的連接

django的文件上傳&JsonResponse的使用&數據庫的連接

id字段 fbv ken 第三章 encode rfi ren 沒有 res

  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‘,
}

django的文件上傳&JsonResponse的使用&數據庫的連接