zoukankan      html  css  js  c++  java
  • python第一百零八天---Django 3 session 操作


    上节内容回顾:
      1 1、请求周期
      2       url> 路由 > 函数或类 > 返回字符串或者模板语言?
      3 
      4       Form表单提交:
      5          提交 -> url > 函数或类中的方法
      6                         - ....
      7                         HttpResponse('....')
      8                         render(request,'index.html')
      9                         redirect('/index/')
     10            用户  <    <  返回字符串
     11           (当接受到redirect时)自动发起另外一个请求
     12           --> url   .....
     13 
     14       Ajax:
     15          $.ajax({
     16             url: '/index/',
     17             data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))}, $(form对象).serilize()
     18             type: 'POST',
     19             dataType: 'JSON':
     20             traditional: true,
     21             success:function(d){
     22                location.reload()              # 刷新
     23                location.href = "某个地址"     # 跳转
     24             }
     25          })
     26          提交 -> url -> 函数或类中的方法
     27                      HttpResponse('{}')
     28                      render(request, 'index.html', {'name': 'v1'})
     29                      <h1>{{ name }}</h1> -->
     30                      <h1>v1</h1>
     31 
     32                      XXXXXXX redirect...
     33          用户 <<<<<  字符串
     34 
     35 
     36    2、路由系统URL
     37       a. /index/                               ->  函数或类
     38       b. /index/(d+)                        ->  函数或类
     39       c. /index/(?P<nid>d+)               ->  函数或类
     40       d. /index/(?P<nid>d+) name='root'         ->  函数或类
     41          reverse()
     42          {% url 'root' 1%}
     43       e. /crm/    include('app01.urls')        -> 路由分发
     44 
     45       f. 默认值
     46          url(r'^index/', views.index, {'name': 'root'}),#在url设置默认值
     47 
     48          def index(request,name):#相关函数需要设置接收的形参
     49             print(name)
     50             return HttpResponse('OK')
     51 
     52       g. 命名空间
     53 
     54          /admin/    include('app01.urls',namespace='m1')
     55          /crm/      include('app01.urls',namespace='m1')
     56 
     57          app01.urls
     58          /index/    name = 'n1'
     59 
     60 
     61          reverser('m1:n1')
     62 
     63    3、后台取数据
     64       def func(request):
     65          request.POST
     66          request.GET
     67          request.FILES
     68          request.getlist
     69          request.method
     70          request.path_info
     71 
     72          return render,HttpResponse,redirect
     73 
     74    4、模板语言
     75       render(request, 'index.html')
     76       # for
     77       # if
     78       # 索引.   keys  values items    all
     79 
     80    5、 数据库 models操作
     81        #创建一个表结构
     82       class User(models.Model):
     83          username = models.CharField(max_length=32)
     84          email = models.EmailField()
     85 
     86       有验证功能
     87          Django Admin
     88       无验证功能:
     89          User.objects.create(username='root',email='asdfasdfasdfasdf')
     90          User.objects.filter(id=1).update(email='666')
     91 
     92 
     93         #创建一个表结构  用户属性表
     94       class UserType(models.Model):
     95          name = models.CharField(max_length=32)
     96 
     97         #创建一个表结构  用户信息表
     98       class User(models.Model):
     99          username = models.CharField(max_length=32)
    100          email = models.EmailField()
    101          user_type = models.ForeignKey("UserType")#外键 关联 UserType 表
    102 
    103       user_list = User.objects.all()#获取User表,所有记录
    104       for obj user_list:
    105          obj.username,obj.email,obj.user_type_id,obj.user_type.name,obj.user_type.id
    106 
    107       user = User.objects.get(id=1)#获取ID为1 的记录 为对象
    108       user.
    109 
    110       User.objects.all().values("username","user_type__name",)#获取所有记录 的username 和 跨表的name
    111 
    112 
    113 
    114       class UserType(models.Model):
    115          name = models.CharField(max_length=32)
    116 
    117         #创建一个表结构  用户信息表
    118       class User(models.Model):
    119          username = models.CharField(max_length=32)
    120          email = models.EmailField()
    121          user_type = models.ForeignKey("UserType")#外键 关联
    122          m = models.ManyToMany('UserGroup')#与 UserGroup 的 第三张关联表 多对多
    123 
    124         #创建一个表结构  用户组表 多对多
    125       class UserGroup(models.Model):
    126          name = ....
    127 
    128 
    129 
    130       obj = User.objects.get(id=1)#获取记录对象
    131       obj.m.add(2)#对第三张表进行添加关联
    132       obj.m.add(2,3)
    133       obj.m.add(*[1,2,3])
    134 
    135       obj.m.remove(...)#对第三张表进行删除关联
    136 
    137       obj.m.clear()#清除当前记录的所有关联关系
    138 
    139       obj.m.set([1,2,3,4,5])#设置关联  (重新所有的设置)
    140 
    141       # 多个组,UserGroup对象
    142       obj.m.all()#
    143       obj.m.filter(name='CTO')#筛选出其中的一个组对象
    View Code



    知识点:
    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')#获取 cookies中的值
                      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
                    #装饰dispatch 后, 等于对类中的每一个函数进行了装饰
                @method_decorator(auth,name='dispatch')#类中的 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 'master.html' %}#  继承母版(子级只能继承一个母版)  master.html 为母版文件
                    {% block title %}xxxxx{% endblock %}#  在母版 设置   子级中对应 可添加子级的专属内容
                include
                    {% include 'tag.html' %}#组件  tag.html为组件  (子级可以加入多个组件)

    - 自定义函数
    simple_tag
    a. app下创建templatetags目录
    b. 任意xxoo.py文件
    c. 创建template对象 register
    - from django.utils.safestring import matk_safe
    register=template.Library()
    d.
    @register.simple_tag
    def func(a1,a2,a3....)
    return "asdfasd"
    e. settings中注册APP
    f. 顶部 {% 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)
        示例:
        views.py
     1 from  utils import pagination
     2 LIST = []
     3 for i in range(500):
     4     LIST.append(i)
     5 
     6 def user_list(request):
     7     current_page = request.GET.get('p', 1)#页面默认第一页
     8     current_page = int(current_page)#转数字
     9 
    10     val = request.COOKIES.get('per_page_count',10) #默认每页 10
    11     print(val)
    12     val = int(val)
    13     page_obj = pagination.Page(current_page,len(LIST),val)#创建类对象 传入  当前页面数值  列表长度   每页显示记录数
    14     #记录数据    开始记录数   结束记录数
    15     data = LIST[page_obj.start:page_obj.end]#  数据记录进行切片取出
    16 
    17     page_str = page_obj.page_str("/user_list/")#开始计算显示的页面
    18 
    19     return render(request, 'user_list.html', {'li': data,'page_str': page_str})
    View Code

      pagination.py

     1 __author__ = 'Administrator'
     2 from django.utils.safestring import mark_safe
     3 
     4 
     5 class Page:
     6     #             当前所在页面   记录条数统计  页面显示记录数   显示的页面数量
     7     def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
     8         self.current_page = current_page#当前当前所在页面
     9         self.data_count = data_count#记录条数统计
    10         self.per_page_count = per_page_count#页面显示记录数
    11         self.pager_num = pager_num#显示的页面数量
    12 
    13     #开始的记录数
    14     @property#装饰后 不用加()
    15     def start(self):
    16         return (self.current_page - 1) * self.per_page_count
    17 
    18     #结束记录数
    19     @property
    20     def end(self):
    21         return self.current_page * self.per_page_count
    22 
    23     #计算当前所有数据 需要的总页面数
    24     @property
    25     def total_count(self):
    26       #商  余   商计算   记录条数统计  页面显示记录数
    27         v, y = divmod(self.data_count, self.per_page_count)
    28         if y:#如果有余数
    29             v += 1#页面数需加1
    30         return v
    31 
    32     #显示页面的方法函数 base_url为要跳转到的页面 ID
    33     def page_str(self, base_url):
    34         page_list = []#想要显示的页面列表
    35         #当 所有的页面数 小于  想要显示的页面数
    36         if self.total_count < self.pager_num:
    37             #从第一页开始
    38             start_index = 1
    39             #到最后一页
    40             end_index = self.total_count + 1
    41 
    42         else:
    43             ##当前所在页面数 小于等于  想要显示的页面数的 +1 的一半  ( 总页面数  大于 想要显示的页面数   应对最前面的页面显示)
    44             if self.current_page <= (self.pager_num + 1) / 2:
    45                 start_index = 1#第一页面
    46                 end_index = self.pager_num + 1#想要显示的页面
    47             else:
    48                 #开始页面为选中页面的 前面几页(想要显示页面的+1的一半数, 选中页面保持中间位置 )
    49                 start_index = self.current_page - (self.pager_num - 1) / 2
    50                 end_index = self.current_page + (self.pager_num + 1) / 2
    51                 #如果 当前所在页面数 + 显示页面的 - 1 的一半 大于总页面数,(应对最后面的显示)
    52                 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
    53                     start_index = self.total_count - self.pager_num + 1
    54                     end_index = self.total_count + 1
    55 
    56         #如果当前为1时
    57         if self.current_page == 1:
    58             #上一页不再跳转
    59             prev = '<a class="page" href="javascript:void(0);">上一页</a>'
    60         else:
    61             prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
    62         page_list.append(prev)
    63         #循环  开始显示页面  结束显示页面
    64         for i in range(int(start_index), int(end_index)):
    65             #如果所选中的页面,加CSS样式
    66             if i == self.current_page:
    67                 temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
    68             else:
    69                 temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
    70             page_list.append(temp)
    71         #如果当前所在页面 等于 最后的页面
    72         if self.current_page == self.total_count:
    73              #下一页不再跳转
    74             nex = '<a class="page" href="javascript:void(0);">下一页</a>'
    75         else:
    76             nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
    77         page_list.append(nex)
    78         #跳转页面 input框
    79         jump = """
    80         <input type='text'  /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
    81         <script>
    82             function jumpTo(ths,base){
    83                 var val = ths.previousSibling.value;
    84                 location.href = base + val;
    85             }
    86         </script>
    87         """ % (base_url,)
    88 
    89         page_list.append(jump)#加入列表
    90 
    91         page_str = mark_safe("".join(page_list))#拼接列表为长字符串
    92 
    93         return page_str
    View Code

     user_list.html

     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>
    21         {% for item in li %}
    22             {% include 'li.html' %}
    23         {% endfor %}
    24     </ul>
    25 
    26     <div>
    27         <select id="ps" onchange="changePageSize(this)">
    28             <option value="10">10</option>
    29             <option value="30">30</option>
    30             <option value="50">50</option>
    31             <option value="100">100</option>
    32         </select>
    33     </div>
    34 
    35     <div class="pagination">
    36         {{ page_str }}
    37     </div>
    38     <script src="/static/jquery-1.12.4.js"></script>
    39     <script src="/static/jquery.cookie.js"></script>
    40     <script>
    41 
    42         $(function(){
    43 {#                var v = $.cookie('per_page_count', {'path': "/user_list/"});#}
    44                 var v = $.cookie('per_page_count');
    45                 $('#ps').val(v);
    46         });
    47 
    48         function changePageSize(ths){
    49             var v = $(ths).val();
    50             console.log(v);
    51             $.cookie('per_page_count',v, {'path': "/user_list/"});
    52 
    53             location.reload();
    54         }
    55     </script>
    56 </body>
    57 </html>
    View Code

    cookie
    客户端浏览器上的一个文件
     1 {"user": 'dachengzi'}
     2 
     3         request.COOKIES.get('username111')#获取 COOKIES的内容
     4 
     5         response = render(request,'index.html')
     6         response = redirect('/index/')
     7         # 设置cookie,关闭浏览器失效
     8         response.set_cookie('key',"value")
     9 
    10         # 设置cookie, N秒只有失效
    11         response.set_cookie('username111',"value",max_age=10)
    12 
    13         # 设置cookie, 截止时间失效
    14         import datetime
    15         current_date = datetime.datetime.utcnow()#现在的时间
    16         current_date = current_date + datetime.timedelta(seconds=5)#  加上5秒
    17         response.set_cookie('username111',"value",expires=current_date)# 等 于5 称后过期
    18         response.set_cookie('username111',"value",max_age=10)
    View Code


  • 相关阅读:
    锁和监视器之间的区别 – Java并发
    实现Runnable接口和继承Thread类之间的区别
    如何使用wait(), notify() and notifyAll() – Java
    HashMap如何工作
    使用hashCode()和equals()方法
    Compare and Swap [CAS] 算法
    对象级别锁 vs 类级别锁 – Java
    solr的访问权限管理及ubuntu下iptables的设置
    mysql 字符串字段中查找非ascii字符
    tensorflow学习——调试ctc的两个bug
  • 原文地址:https://www.cnblogs.com/uge3/p/7406867.html
Copyright © 2011-2022 走看看