昨日内容回顾
\'\'\'1. urlencoded2. form-data3. json\'\'\'1. ajax$.ajax({data: JSON.stringify({\'d1\':1}),contentType:\'application/json\'})2. api工具
1. form表单2. ajaxvar myfile = $(\'#myfile\')[0].files[0];var myFormData = new FormData();myFormData.append(\'username\', \'1\');myFormData.append(\'password\', \'2\');# 添加文件数据myFormData.append(\'myfile\', myfile);$.ajax({data:myFormData,# 指定两个参数contentType:false,processData:false})
今日内容概要
- 批量插入数据
- 分页原理和分页类的使用
- cookie和session介绍
- django如何操作cookie
内容详细
1. 批量插入数据
# 准备数据:1.更改配置文件 settings.py:DATABASES = {# \'default\': {# \'ENGINE\': \'django.db.backends.sqlite3\',# \'NAME\': os.path.join(BASE_DIR, \'db.sqlite3\'),# }\'default\': {\'ENGINE\': \'django.db.backends.mysql\',\'NAME\': \'day09\',\'HOST\': \'127.0.0.1\',\'PORT\': 3306,\'USER\': \'root\',\'PASSWORD\': \'123\',\'CHARSET\': \'utf8\'}}2.任一__init__.py文件中写入:import pymysqlpymysql.install_as_MySQLdb()3.在models.py文件中创建表:class Book(models.Model):title = models.CharField(max_length=32)4.完成数据库迁移:makemigrationsmigrate# 在tests.py文件中测试:import osimport sysif __name__ == \'__main__\':os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite9.settings")import djangodjango.setup()# 代码写在此处以下# 向表中插入十万条数据from app01 import models# 方法一:# for i in range(100000): # 效率太低# models.Book.objects.create(title=\'第%s本书\' % i)# 方法二:# l = []# for i in range(100000):# res = models.Book(title=\'第%s本书\' % i)# l.append(res)# models.Book.objects.bulk_create(l)# 补充:随机生成固定格式数据模块 fakerfrom faker import Fakerfaker = Faker(\'zh_CN\')print(faker.name())print(faker.email())print(faker.phone_number())
2. 分页原理
总数据100每页展示10条# 1.在 views.py文件写入:from app01 import modelsdef index(request):current_page = request.GET.get(\'page\', 1) # 默认值第1页try:current_page = int(current_page)except Exception:current_page = 1all_book_list = models.Book.objects.all()total = len(all_book_list)# 每页展示多少条数据per_page_num = 10# 得到总页数total_page, b = divmod(total, per_page_num)if b:total_page += 1aaa= current_pagehtml = \'\'if current_page < 6:current_page = 6for i in range(current_page-5, current_page+6):if aaa == i:html += \'<li class="active"><a href="?page=%s">%s</a></li>\' % (i, i)else:html += \'<li><a href="?page=%s">%s</a></li>\' % (i, i)start = (aaa - 1) * per_page_numend = aaa * per_page_numbook_list = all_book_list[start:end]return render(request, \'index.html\', locals())# 2.新建index.html文件:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script></head><body>{% for book in book_list %}<p>{{ book.title }}</p>{% endfor %}<nav aria-label="Page navigation"><ul class="pagination"><li><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>{{ html|safe }}<li><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li></ul></nav></body></html># 3.在urls.py文件中添加路由:url(r\'^index/\', views.index),# 4.在测试文档 tests.py文件中添加1000条数据到表中:l = []for i in range(1000):res = models.Book(title=\'第%s本书\' % i)l.append(res)models.Book.objects.bulk_create(l)# 别人自行写好的:class Pagination(object):def __init__(self, current_page, all_count, per_page_num=2, pager_count=5):"""封装分页相关数据: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_numdef 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)
3. cookie和session介绍
1. 很久以前,网站都是静态的,eg: 新闻类,博客类# 静态网站不需要登录2. 随着发展,后续诞生了支付宝,购物网站...# 动态网站需要登录3. HTTP协议的特点:3.1 无状态诞生了保存用户数据的cookie,session,token4. cookie介绍cookie把数据保存在浏览器上,以登录功能为例,cookie的工作原理:"""当用户第一次登录成功之后,django后端把用户数据保存在浏览器上,浏览器会自动把用户数据提交到django后端,django接收传过来的用户信息,再次做验证,如果正确,则正常登录"""# 用户名和密码存在浏览器上,不安全5. 为了解决浏览器数据不安全问题,诞生了sessionsession解决的是安全问题,把数据保存在后端,在django中,session把数据保存在数据库中(默认保存的),session会把数据保存在django生成的django_session表中# 工作原理:当用户第一次登录成功之后,django会自动生成一个随机字符串,与用户的真实信息做一个对应:随机字符串1:用户信息1随机字符串2:用户信息2随机字符串3:用户信息3django会把随机字符串返回给浏览器,说白了,把随机字符串保存在cookie里了,当用户再次进入网站的时候,浏览器会自动把随机字符串提交过来,django会拿着随机字符串去django_session表中查找对应的信息,如果有,则说明已经登录了,如果没有,说明没有登录6. session是基于cookie工作的?# 正确7. 如果用户主动进制了cookie,那么,session就一定不能用了?# 不是7.1 把随机字符串以参数的形式提交到django7.2 把数据放到请求头中# 总结:1. cookie的数据保存在浏览器2. session的数据保存在数据库,session的保存位置是可以更改的:2.1 文件2.2 数据库2.3 redis2.4 memcache2.5 消息队列3. 专业的消息队列工具:3.1 kafka3.2 rabbitmq3.3 HTTPsqs4. session是基于cookie工作
4. django操作cookie
1. obj = HttpResponse()2. obj = redirect3. obj = render# django要想操作cookie,就必须借助于HttpResponse# eg:登录功能01 在views.py文件中写入:from django.shortcuts import render, HttpResponse, redirectfrom app01 import modelsdef login(request):if request.method == \'POST\':username = request.POST.get(\'username\')password = request.POST.get(\'password\')userinfo = models.Book.objects.filter(username=username, password=password).first()if userinfo:# 保存用户信息obj = HttpResponse(\'登录成功\')# 保存数据到cookieobj.set_cookie(\'username\', userinfo.username, max_age=120) # max_age 时间 秒 过时数据自动清空obj.set_cookie(\'id\', userinfo.id)return objreturn render(request, \'login.html\')# 判断不登录不让访问def home(request):if request.COOKIES.get(\'username\'):return HttpResponse(\'已经登录\')else:return redirect(\'/login/\')02 补充表数据 在models.py中:class Book(models.Model):title = models.CharField(max_length=32)username = models.CharField(max_length=32, null=True)password = models.CharField(max_length=32, null=True)03 添加路由urls.py中:url(r\'^login/\', views.login),url(r\'^home/\', views.home),04 新建 login.html文件:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script></head><body><form action="" method="post"><p><input type="text" name="username"></p><p><input type="text" name="password"></p><input type="submit" value="提交"></form></body></html>