python学习笔记_week21
note
View Code
上节内容回顾: 1、请求周期 url> 路由 > 函数或类 > 返回字符串或者模板语言? Form表单提交: 提交 -> url > 函数或类中的方法 - .... HttpResponse('....') render(request,'index.html') redirect('/index/') 用户 < < 返回字符串 (当接受到redirect时)自动发起另外一个请求 --> url ..... Ajax: $.ajax({ url: '/index/', data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))}, $(form对象).serilize() type: 'POST', dataType: 'JSON': traditional: true, #多选(如下拉框)要加traditional success:function(data){ #回调函数 location.reload() # 刷新 location.href = "某个地址" # 跳转 } }) 提交 -> url -> 函数或类中的方法 HttpResponse('{}') #可定制性更高 render(request, 'index.html', {'name': 'v1'}){{ name }}
--> #用户拿到不能做特殊的处理v1
XXXXXXX redirect...不可以 ,只能reload,href 用户 <<<<< 字符串 2、路由系统URL a. /index/ -> 函数或类 b. /index/(\d+) -> 函数或类 c. /index/(?P\d+) -> 函数或类 d. /index/(?P \d+) name='root' -> 函数或类 reverse() {% url 'root' 1%} e. /crm/ include('app01.urls') -> 路由分发 f. 默认值 url(r'^index/', views.index, {'name': 'root'}), def index(request,name): print(name) return HttpResponse('OK') g. 命名空间 #用于函数生成url /admin/ include('app01.urls',namespace='m1') /crm/ include('app01.urls',namespace='m2') app01.urls /index/ name = 'n1' reverser('m1:n1') 3、 def func(request): request.POST request.GET request.FILES request.getlist request.method request.path_info return render,HttpResponse,redirect 4、 render(request, 'index.html') # for # if # 索引. keys values items all 5、 class User(models.Model): username = models.CharField(max_length=32) email = models.EmailField() 有验证功能 Django Admin 无验证功能: User.objects.create(username='root',email='asdfasdfasdfasdf') User.objects.filter(id=1).update(email='666') class UserType(models.Model): name = models.CharField(max_length=32) class User(models.Model): username = models.CharField(max_length=32) email = models.EmailField() user_type = models.ForeignKey("UserType") user_list = User.objects.all() for obj user_list: #对象列表 obj.username,obj.email,obj.user_type_id,obj.user_type.name,obj.user_type.id user = User.objects.get(id=1) #单个对象 user. User.objects.all().values("username","user_type__name",) #注意__ class UserType(models.Model): name = models.CharField(max_length=32) class User(models.Model): username = models.CharField(max_length=32) email = models.EmailField() user_type = models.ForeignKey("UserType") m = models.ManyToMany('UserGroup') class UserGroup(models.Model): name = .... obj = User.objects.get(id=1) obj.m.add(2) obj.m.add(2,3) obj.m.add(*[1,2,3]) obj.m.remove(...) obj.m.clear() obj.m.set([1,2,3,4,5]) obj.m.all() # 多个组,UserGroup对象 obj.m.filter(name='CTO') 知识点: URL - 两个 Views - 请求的其他信息 from django.core.handlers.wsgi import WSGIRequest request.environ request.environ['HTTP_USER_AGENT'] - 装饰器 FBV: def auth(func): def inner(reqeust,*args,**kwargs): v = reqeust.COOKIES.get('username111') if not v: return redirect('/login/') return func(reqeust, *args,**kwargs) return inner CBV: from django import views from django.utils.decorators import method_decorator @method_decorator(auth,name='dispatch') class Order(views.View): # @method_decorator(auth) # def dispatch(self, request, *args, **kwargs): # return super(Order,self).dispatch(request, *args, **kwargs) # @method_decorator(auth) def get(self,reqeust): v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v}) def post(self,reqeust): v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v}) Templates - 母版...html ---可以模板渲染(会自动搞到一起再渲染) extends 只能继承一个母版 include 可以有多个 - 自定义函数 simple_tag a. app下创建templatetags目录 #templatetags目录名不能改 b. 任意xxoo.py文件 c. 创建template对象 register(对象名)不能改 d. @register.simple_tag def func(a1,a2,a3....) return "asdfasd" e. settings中注册APP f. html顶部 {% load xxoo %} g. {% 函数名 arg1 arg2 %} #空格没关系 缺点: 不能作为if条件 优点: 参数任意 filter a. app下创建templatetags目录 b. 任意xxoo.py文件 c. 创建template对象 register d. @register.filter def func(a1,a2) return "asdfasd" e. settings中注册APP f. 顶部 {% load xxoo %} g. {{ 参数1|函数名:"参数二,参数三" }} {{ 参数1|函数名:数字 }} 缺点: 最多两个参数,不能加空格 优点: 能作为if条件 分页(自定义的分页) XSS: {{ page_str|safe }} mark_safe(page_str) cookie 客户端浏览器上的一个文件 {"user": 'dachengzi'} 参数: key, 键 value='', 值 max_age=None, 超时时间 expires=None, 超时时间(IE requires expires, so set it if hasn't been already.) path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问 domain=None, Cookie生效的域名 secure=False, https传输 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖) session :装饰器 Models - 一大波操作 Form验证 - 缓存 中间件 信号 CSRF Admin/ModelForm 作业: 主机管理: 1、单表操作 2、一对多 3、多对多 要求: a. 删除对话框 b. 修改,添加新URL c. 基于cookie进行用户认证 d. 定制显示个数 e. 分页 预习: Form: http://www.cnblogs.com/wupeiqi/articles/6144178.html Model:http://www.cnblogs.com/wupeiqi/articles/6216618.html
views
View Code
1 from django.shortcuts import render, HttpResponse,redirect 2 from django.urls import reverse 3 # Create your views here. 4 # def index(request): 5 # # v = reverse('author:index') 6 # # print(v) 7 # from django.core.handlers.wsgi import WSGIRequest 8 # # print(type(request)) 9 # #封装了所有用户请求信息 10 # # print(request.environ) 11 # # for k,v in request.environ.items(): 12 # # print(k,v) 13 # # print(request.environ['HTTP_USER_AGENT']) 14 # # request.POST 15 # # request.GET 16 # # request.COOKIES 17 # 18 # return HttpResponse('OK') 19 def tpl1(request): 20 user_list = [1, 2, 3, 43] 21 return render(request, 'tpl1.html', {'u': user_list}) 22 def tpl2(request): 23 name = 'root' 24 return render(request, 'tpl2.html', {'name': name}) 25 def tpl3(request): 26 status = "已经删除" 27 return render(request, 'tpl3.html', {'status': status}) 28 def tpl4(request): 29 name = "IYMDFjfdf886sdf" 30 return render(request, 'tpl4.html', {'name': name}) 31 from utils import pagination 32 LIST = [] 33 for i in range(500): 34 LIST.append(i) 35 def user_list(request): 36 current_page = request.GET.get('p', 1) #1表示默认显示第一页 37 current_page = int(current_page) 38 val = request.COOKIES.get('per_page_count',10) 39 print(val) 40 val = int(val) 41 page_obj = pagination.Page(current_page,len(LIST),val) 42 data = LIST[page_obj.start:page_obj.end] 43 page_str = page_obj.page_str("/user_list/") 44 return render(request, 'user_list.html', {'li': data,'page_str': page_str}) 45 ########################### cookie ########################### 46 user_info = { 47 'dachengzi': {'pwd': "123123"}, 48 'kanbazi': {'pwd': "kkkkkkk"}, 49 } 50 def login(request): 51 if request.method == "GET": 52 return render(request,'login.html') 53 if request.method == "POST": 54 u = request.POST.get('username') 55 p = request.POST.get('pwd') 56 dic = user_info.get(u) 57 if not dic: 58 return render(request,'login.html') 59 if dic['pwd'] == p: 60 res = redirect('/index/') 61 # res.set_cookie('username111',u,max_age=10) 62 # import datetime 63 # current_date = datetime.datetime.utcnow() 64 # current_date = current_date + datetime.timedelta(seconds=5) 65 # res.set_cookie('username111',u,expires=current_date) 66 res.set_cookie('username111',u) 67 res.set_cookie('user_type',"asdfjalskdjf",httponly=True) #httponly用js获取不到 68 return res 69 else: 70 return render(request,'login.html') 71 def auth(func): 72 def inner(reqeust,*args,**kwargs): 73 v = reqeust.COOKIES.get('username111') 74 if not v: 75 return redirect('/login/') 76 return func(reqeust, *args,**kwargs) 77 return inner 78 @auth 79 def index(reqeust): 80 # 获取当前已经登录的用户 81 v = reqeust.COOKIES.get('username111') 82 return render(reqeust,'index.html',{'current_user': v}) 83 from django import views 84 from django.utils.decorators import method_decorator 85 @method_decorator(auth,name='dispatch') 86 class Order(views.View): 87 # @method_decorator(auth) 88 # def dispatch(self, request, *args, **kwargs): 89 # return super(Order,self).dispatch(request, *args, **kwargs) 90 # @method_decorator(auth) 91 def get(self,reqeust): 92 v = reqeust.COOKIES.get('username111') 93 return render(reqeust,'index.html',{'current_user': v}) 94 def post(self,reqeust): 95 v = reqeust.COOKIES.get('username111') 96 return render(reqeust,'index.html',{'current_user': v}) 97 def order(reqeust): 98 # 获取当前已经登录的用户 99 v = reqeust.COOKIES.get('username111') 100 return render(reqeust,'index.html',{'current_user': v}) 101 def cookie(request): 102 # request.COOKIES 103 # request.COOKIES['username111'] 104 request.COOKIES.get('username111') #获取cookie 105 response = render(request,'index.html') 106 response = redirect('/index/') 107 response.set_cookie('key',"value")# 设置cookie,关闭浏览器失效 108 response.set_cookie('username111',"value",max_age=10)# 设置cookie, N秒只有失效 109 import datetime 110 current_date = datetime.datetime.utcnow() 111 current_date = current_date + datetime.timedelta(seconds=5) 112 response.set_cookie('username111',"value",expires=current_date) # 设置cookie, 截止时间失效 113 response.set_cookie('username111',"value",max_age=10) 114 # request.COOKIES.get('...') 115 # response.set_cookie(...) 116 obj = HttpResponse('s') 117 obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf") #加密文 118 request.get_signed_cookie('username',salt="asdfasdf") #解密 119 return response
urls
View Code
1 from django.conf.urls import url,include 2 from django.contrib import admin 3 from app01 import views 4 urlpatterns = [ 5 # url(r'^admin/', admin.site.urls), 6 # url(r'^index/', views.index), 7 # url(r'^index/', views.index, {'name': 'root'}), 8 # url(r'^a/', include('app01.urls', namespace='author')), 9 url(r'^tpl1/', views.tpl1), 10 url(r'^tpl2/', views.tpl2), 11 url(r'^tpl3/', views.tpl3), 12 url(r'^tpl4/', views.tpl4), 13 url(r'^user_list/', views.user_list), 14 url(r'^login/', views.login), 15 url(r'^index/', views.index), 16 url(r'^order/', views.Order.as_view()), 17 ]
index
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 head> 7 <body> 8 <h1>欢迎登录:{{ current_user }}h1> 9 body> 10 html>
li
View Code
1 <li>{{ item }}li>
login
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 head> 7 <body> 8 <form action="/login/" method="POST"> 9 <input type="text" name="username" placeholder="用户名" /> 10 <input type="password" name="pwd" placeholder="密码" /> 11 <input type="submit" /> 12 form> 13 body> 14 html>
master
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>{% block title %} {% endblock %}title> 6 <link rel="stylesheet" href="/static/commons.css" /> 7 <style> 8 .pg-header{ 9 height: 50px; 10 background-color: seashell; 11 color: green; 12 } 13 style> 14 {% block css %} {% endblock %} 15 head> 16 <body> 17 <div class="pg-header">小男孩管理div> 18 <div> 19 <a>asdfa> 20 <a id="">asdfa> 21 <a>asdfa> 22 <a>asdfa> 23 <a>asdfa> 24 div> 25 <iframe src="/">iframe> 26 body> 27 html>
tp1.bak
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 <link rel="stylesheet" href="/static/commons.css" /> 7 <style> 8 .pg-header{ 9 height: 48px; 10 background-color: seashell; 11 color: green; 12 } 13 style> 14 head> 15 <body> 16 <div class="pg-header">小男孩管理div> 17 <h1>用户管理h1> 18 <ul> 19 {% for i in u %} 20 <li>{{ i }}li> 21 {% endfor %} 22 ul> 23 <script src="/static/jquery.js">script> 24 body> 25 html>
tp1
View Code
1 {% extends 'master.html' %} 2 {% block title %}用户管理{% endblock %} 3 {% block content %} 4 <h1>用户管理h1> 5 <ul> 6 {% for i in u %} 7 <li>{{ i }}li> 8 {% endfor %} 9 ul> 10 {% for i in u %} 11 {% include 'tag.html' %} 12 {% endfor %} 13 {% endblock %} 14 {% block css %} 15 <style> 16 body{ 17 background-color: red; 18 } 19 style> 20 {% endblock %} 21 {% block js %} 22 <script>script> 23 {% endblock %}
tp2
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 <link rel="stylesheet" href="/static/commons.css" /> 7 <style> 8 .pg-header{ 9 height: 48px; 10 background-color: seashell; 11 color: green; 12 } 13 style> 14 head> 15 <body> 16 <div class="pg-header">小男孩管理div> 17 <h1>修改密码{{ name }}h1> 18 <script src="/static/jquery.js">script> 19 body> 20 html>
tp3
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 <link rel="stylesheet" href="/static/commons.css" /> 7 <style> 8 .pg-header{ 9 height: 48px; 10 background-color: seashell; 11 color: green; 12 } 13 style> 14 head> 15 <body> 16 <div class="pg-header">小女孩管理div> 17 <h3> {{ status }}h3> 18 <script src="/static/jquery.js">script> 19 body> 20 html>
tp4
View Code
1 {% load xxoo %} 2 DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>title> 7 head> 8 <body> 9 {{ name }} 10 {{ name|lower }} 11 {{ name|truncatechars:"3" }} 12 {% houyafan 2 5 6 %} 13 {{ "maliya"|jiajingze:30 }} 14 body> 15 html>
user_list
View Code
1 DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>title> 6 <style> 7 .pagination .page{ 8 display: inline-block; 9 padding: 5px; 10 background-color: cyan; 11 margin: 5px; 12 } 13 .pagination .page.active{ 14 background-color: brown; 15 color: white; 16 } 17 style> 18 head> 19 <body> 20 <ul id="len"> 21 {% for item in li %} 22 {% include 'li.html' %} 23 {% endfor %} 24 ul> 25 <div> 26 <select id="ps" onchange="changePageSize(this)"> 27 <option value="10">10option> 28 <option value="30">30option> 29 <option value="50">50option> 30 <option value="100">100option> 31 select> 32 div> 33 <div class="pagination"> 34 {{ page_str }} 35 div> 36 <script src="/static/jquery-1.12.4.js">script> 37 <script src="/static/jquery.cookie.js">script> 38 <script> 39 $(function(){ 40 var v = $.cookie('per_page_count',$("#len li").length,{'path': "/user_list/`"}); 41 console.log(v); 42 $('#ps').val($("#len li").length); 43 }); 44 function changePageSize(ths){ 45 var v = $(ths).val(); 46 console.log(v); 47 $.cookie('per_page_count',v, {'path': "/user_list/"}); 48 location.reload(); 49 } 50 script> 51 body> 52 html>
pagination
View Code
1 from django.utils.safestring import mark_safe 2 class Page: 3 def __init__(self, current_page, data_count, per_page_count=10, pager_num=7): 4 self.current_page = current_page 5 self.data_count = data_count 6 self.per_page_count = per_page_count 7 self.pager_num = pager_num 8 @property 9 def start(self): 10 return (self.current_page - 1) * self.per_page_count 11 @property 12 def end(self): 13 return self.current_page * self.per_page_count 14 @property 15 def total_count(self): 16 v, y = divmod(self.data_count, self.per_page_count) 17 if y: 18 v += 1 19 return v 20 def page_str(self, base_url): 21 page_list = [] 22 if self.total_count < self.pager_num: 23 start_index = 1 24 end_index = self.total_count + 1 25 else: 26 if self.current_page <= (self.pager_num + 1) / 2: 27 start_index = 1 28 end_index = self.pager_num + 1 29 else: 30 start_index = self.current_page - (self.pager_num - 1) / 2 31 end_index = self.current_page + (self.pager_num + 1) / 2 32 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count: 33 end_index = self.total_count + 1 34 start_index = self.total_count - self.pager_num + 1 35 if self.current_page == 1: 36 prev = '上一页' 37 else: 38 prev = '上一页' % (base_url, self.current_page - 1,) 39 page_list.append(prev) 40 for i in range(int(start_index), int(end_index)): 41 if i == self.current_page: 42 temp = '%s' % (base_url, i, i) 43 else: 44 temp = '%s' % (base_url, i, i) 45 page_list.append(temp) 46 if self.current_page == self.total_count: 47 nex = '下一页' 48 else: 49 nex = '下一页' % (base_url, self.current_page + 1,) 50 page_list.append(nex) 51 jump = """ 52 GO 53 59 """ % (base_url,) 60 page_list.append(jump) 61 page_str = mark_safe("".join(page_list)) 62 return page_str
posted on
2018-01-18 08:47 我很好u 阅读(
...) 评论(
...) 编辑 收藏