前后端數據傳輸的編碼格式(contentType)
# 我們只研究post請求方式的編碼格式:
?????????? ?get請求方式沒有編碼格式--?index?useranme=&password=
?? ?????????get請求方式沒有請求體,參數直接在url地址的后面拼接著#?有哪些方式可以提交post請求:form表單、Ajax、api工具
# 研究form表單的post請求:
????????? 默認的編碼格式:urlencoded
????????? 數據傳輸的形式:title=dasdas&price=2312&date=&publish=2&authors=3# 對于Django后端是如何接收數據的:
????????把提交過來的數據都封裝到了request.POST中
# 提交文件數據:enctype:form-data
# 數據傳輸的形式:
? ? ? ? ? ?title=dasdas&price=2312&date=&publish=2&authors=3????????--------------binary-----------------------------
? ? ? ? ? ? ? ? ? ? ? ?文件數據# 對于Django后端接收數據的:
????????普通數據還是在request.POST中
????????文件數據呢還是在request.FILES中
能在POST和FILES中接收數據,是因為Django已封裝了,提交過來的數據并不是queryDICT# ajax提交post請求:
????????默認情況下,Ajax提交的數據后端還是在request.POST中接收的
????????默認的編碼格式:urlencoded
????????需要修改contentType類型:json格式的"""對于符合urlencoded格式的數據后端都是在request.POST中接收數據的"""
Ajax提交json格式的數據
views.py def index(request):if request.method == 'POST':print(request.POST) #<QueryDict: {}>print(request.body) #b'{"a":1,"b":2}'json_bytes=request.body # 接收瀏覽器發過來純原生的數據,二進制,需要自己做封裝# json_str=json_bytes.decode('utf-8')# print(json_str,type(json_str)) # {"a":1,"b":2} <class 'str'>import json# json_dict = json.loads(json_str)# print(json_dict,type(json_dict)) # {'a': 1, 'b': 2} <class 'dict'>json_dict = json.loads(json_bytes)print(json_dict,type(json_dict)) # {'a': 1, 'b': 2} <class 'dict'>return render(request,'index.html')
index.html <body> <button class="btn">提交</button> <script>$(".btn").click(function () {$.ajax({url:'',type:'post',data:JSON.stringify({a:1,b:2}), //序列化contentType:'application/json', //json格式的success:function (res){}})}) </script> </body>
前端提交到后端,后端json解碼
Ajax提交文件數據
index.html <body> <form action="">用戶名: <input type="text" id="username">上傳文件: <input type="file" id="myfile"><button class="btn">提交</button> <script>$(".btn").click(function (ev) {console.log(123);// 要獲取到文件數據,{#console.log($("#myfile")[0].files[0]) // C:\fakepath\123.png#}// 提交文件數據需要借助于formdata對象var myFormDataObj = new FormData;var username = $("#username").val();var myfile = $("#myfile")[0].files[0];myFormDataObj.append('username', username);myFormDataObj.append('myfile',myfile);$.ajax({url: '',type: 'post',{#data: JSON.stringify({a: 1, b: 2}), // 序列化的 "{"a":1, "b":2}"#}data: myFormDataObj, // 序列化的 "{"a":1, "b":2}"{#contentType: 'application/json', // json格式的#}contentType:false, // 告訴瀏覽器不要給我的編碼格式做任何的處理processData: false, //success: function (res) {}})}) </script> </body>
Ajax結合layer 彈出層組件
layer 彈出層組件 - jQuery 彈出層插件 (layuiweb.com)
批量插入數據
bulk_list = [] for i in range(10000):user_obj=models.UserInfo(username='kevin%s' %i)bulk_list.append(user_obj) models.UserInfo.objects.bulk_create(bulk_list)
# 循環之后得到了一個列表,10000個對象
# 數據庫的優化, 同樣的功能,不同的sql執行的效率差距很大
# 優化查詢速度的時候,首先想到的是,加索引、優化sql語句,有的sql走做引、有的sql不走索引
分頁的原理及推導
當查詢的數據太多的時候,一頁展示不完,分頁碼展示
總數據? 每頁展示 總頁數 100?? ? 10 10
101 10 11 99 10 10 怎么計算出來總頁數:? ?總數據 ?/ ?每頁展示 ?= ?總頁數? ? ? ? ??divmod
????????有余數+1
????????沒有余數=商
分頁類
以后使用直接導入文件用就行,已經封裝好,需配置路由和鏈接數據庫使用
utils/my_page.py class Pagination(object):def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):"""封裝分頁相關數據:param current_page: 當前頁:param all_count: 數據庫中的數據總條數:param per_page_num: 每頁顯示的數據條數:param pager_count: 最多顯示的頁碼個數"""try:current_page = int(current_page)except Exception as e:current_page = 1if current_page < 1:current_page = 1self.current_page = current_pageself.all_count = all_countself.per_page_num = per_page_num# 總頁碼all_pager, tmp = divmod(all_count, per_page_num)if tmp:all_pager += 1self.all_pager = all_pagerself.pager_count = pager_countself.pager_count_half = int((pager_count - 1) / 2)@propertydef start(self):return (self.current_page - 1) * self.per_page_num@propertydef end(self):return self.current_page * self.per_page_num@propertydef page_html(self):# 如果總頁碼 < 11個:if self.all_pager <= self.pager_count:pager_start = 1pager_end = self.all_pager + 1# 總頁碼 > 11else:# 當前頁如果<=頁面上最多顯示11/2個頁碼if self.current_page <= self.pager_count_half:pager_start = 1pager_end = self.pager_count + 1# 當前頁大于5else:# 頁碼翻到最后if (self.current_page + self.pager_count_half) > self.all_pager:pager_end = self.all_pager + 1pager_start = self.all_pager - self.pager_count + 1else:pager_start = self.current_page - self.pager_count_halfpager_end = self.current_page + self.pager_count_half + 1page_html_list = []# 添加前面的nav和ul標簽page_html_list.append('''<nav aria-label='Page navigation>'<ul class='pagination'>''')first_page = '<li><a href="?page=%s">首頁</a></li>' % (1)page_html_list.append(first_page)if self.current_page <= 1:prev_page = '<li class="disabled"><a href="#">上一頁</a></li>'else:prev_page = '<li><a href="?page=%s">上一頁</a></li>' % (self.current_page - 1,)page_html_list.append(prev_page)for i in range(pager_start, pager_end):if i == self.current_page:temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)else:temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)page_html_list.append(temp)if self.current_page >= self.all_pager:next_page = '<li class="disabled"><a href="#">下一頁</a></li>'else:next_page = '<li><a href="?page=%s">下一頁</a></li>' % (self.current_page + 1,)page_html_list.append(next_page)last_page = '<li><a href="?page=%s">尾頁</a></li>' % (self.all_pager,)page_html_list.append(last_page)# 尾部添加標簽page_html_list.append('''</nav></ul>''')return ''.join(page_html_list)
ab_page.html <body> {% for foo in userlist %}<p>{{ foo.username }}</p> {% endfor %}{{ html|safe }} </body>
views.py from django.shortcuts import render from app01 import models def ab_page(request):from utils.my_page import Paginationtry:current_page = int(request.GET.get('page'))except:current_page = 1user_queryset = models.UserInfo.objects.all()all_count = user_queryset.count()page_obj = Pagination(current_page, all_count, per_page_num=10)userlist = user_queryset[page_obj.start:page_obj.end]html = page_obj.page_htmlreturn render(request, 'ab_page.html', locals())""" per_page_num=10 current_page start_page end_page 1 0 10 2 10 20 3 20 30 start_page=(current_page - 1) * per_page_num end_page=current_page*per_page_num """