Django补充(三)之路由系统URL、自定义函数、自定义分页、Cookie操作、FBV和CBV

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dream_ya/article/details/86604828

上一篇文章>Django入门(二)之一对多和多对多表结构操作、Ajax提交

一、本机环境


操作系统:rhel7.3
Python版本:python3.6
Django版本:Django-2.1.5
[root@python _Django]# tree project1
project1
├── app
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-36.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-36.pyc
│   │   ├── __init__.cpython-36.pyc
│   │   ├── models.cpython-36.pyc
│   │   └── views.cpython-36.pyc
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── project1
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static
│   └── jquery-1.12.4.min.js
└── templates

二、路由系统URL


1、传入默认值(形参)

(1)配置urls.py
[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index, {'name': 'dream'}),
]
(2)运行访问
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse

def index(request,name):
    print (name)
    return HttpResponse('OK')
[root@python project1]# python manage.py makemigrations
[root@python project1]# python manage.py migrate
[root@python project1]# python manage.py runserver 10.10.10.111:8000

http://10.10.10.111:8000/index/            ###浏览器访问

2、命名空间(namespace)

(1)配置project1/urls.py
[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include

urlpatterns = [
    # path('admin/', admin.site.urls),
    # path('index/', views.index, {'name': 'dream'}),
    path('a/', include('app.urls', namespace='author'))
]
(2)配置app/urls.py
[root@python project1]# vim app/urls.py
from django.contrib import admin
from django.urls import path
from app import views
app_name = 'app'
urlpatterns = [
    path('index/', views.index, name='index'),
]
(3)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse

def index(request):
    v = reverse('author:index')
    print (v)
    return HttpResponse('OK')
(4)访问
http://10.10.10.111:8000/a/index/

3、Views(请求其他信息)

[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse

def index(request):
    v = reverse('author:index')
    print (v)
    print (type(request))
    # from django.core.handlers.wsgi import WSGIRequest   ###查看源码

    # print (request.environ)
    ### 获取key,value
    # for k,v in request.environ.items():
    #     print (k,v)

    ### 获取数据来源是否是pc
    print (request.environ['HTTP_USER_AGENT'])
    return HttpResponse('OK')

4、模板继承(templates)

(1)配置urls.py
[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include
urlpatterns = [
    path('tpl/', views.tpl),
]
(2)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse

def index(request):
    v = reverse('author:index')
    print (v)
    print (type(request))
    print (request.environ['HTTP_USER_AGENT'])
    return HttpResponse('OK')
    
def tpl(request):
    user_list = [1,2,3,4]
    return render(request, 'tpl.html', {'user_list': user_list,})
(3)配置HTML

<1> 配置model.html

[root@python project1]# vim templates/model.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>
    <!--<link rel="stylesheet" href="/static/commons.css">-->
    <style>
    .pg-header {
        background-color: #b9def0;
        color: aqua;
    }
    </style>
    {% block css %} {% endblock %}
</head>
<body>
	<div class="pg-header">Dream</div>
	<div class="tt">Dreamya</div>
	{% block content %} {% endblock %}
	<!--<script src="/static/query-1.12.4.min.js"></script>-->
	{% block js %} {% endblock %}
</body>
</html>

<2> 配置tpl.html

[root@python project1]# vim templates/tpl.html
{% extends 'model.html' %}
{% block title %}tpl-title{% endblock %}
{% block css %}
    <style>
        .tt{
            background-color: red;
            width: 100px;
        }
    </style>
{% endblock %}

{% block content %}
<div class="tt">-----tpl-----</div>
<ul>
    {% for i in user_list %}
    <li>Dream-{{ i }}</li>
    {% endfor %}
</ul>
{% endblock %}
(4)访问
http://10.10.10.111:8000/tpl/ 

5、模板导入

通过include我们可以实现把tag.html的内容导入到自身HTML中!!!

(1)配置tpl.html
[root@python project1]# vim templates/tpl.html
{% extends 'model.html' %}
{% block title %}tpl-title{% endblock %}
{% block css %}
    <style>
        .tt{
            background-color: red;
            width: 100px;
        }
    </style>
{% endblock %}

{% block content %}
<div class="tt">-----tpl-----</div>
<ul>
    {% for i in user_list %}
    <li>Dream-{{ i }}</li>
    {% endfor %}
</ul>
{% include 'tag.html' %}
{% include 'tag.html' %}
{% endblock %}
(2)配置HTML
[root@python project1]# vim templates/tag.html
<div>
    <input type="text"/>
</div>

三、自定义函数


1、自定义simple_tag

(1)介绍
simple_tag:
		a. app下创建templatetags目录
		b. 任意tag.py文件
		c. 创建template对象 register(名字不能更改)
		d. 
			@register.simple_tag
			def func(a1,a2,a3....)
				return "xxx"
		e. settings中注册APP
		f. 顶部 {% load tag %}
		g. {% 函数名 arg1 arg2 %}
		缺点:
			不能作为if条件
		优点:
			参数任意
(2)配置tag.py
[root@python project1]# mkdir app/templatetags/
[root@python project1]# vim app/templatetags/tag.py
#!/usr/bin/env python
# coding:utf-8
from django import template
register = template.Library()
@register.simple_tag
def add(a, b):
    return a + b
(3)配置settings.py
[root@python project1]# vim project1/settings.py

在这里插入图片描述

(4)配置HTML
[root@python project1]# vim templates/tpl2.html
{% load tag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}
    {% add 2 3 %}
</body>
</html>
(5)配置views.py
[root@python project1]# vim app/views.py     ###加入
def tpl2(request):
    return render(request, 'tpl2.html', {'name': "DREAMya"})
(6)配置urls.py
[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include
urlpatterns = [
    path('tpl/', views.tpl),
    path('tpl2/', views.tpl2),
]
http://10.10.10.111:8000/tpl2/

2、自定义filter

(1)介绍
filter:
		a. app下创建templatetags目录
		b. 任意tag.py文件
		c. 创建template对象 register(名字不能更改)
		d. 
			@register.simple_tag
			def func(a1,a2,a3....)
				return "xxx"
		e. settings中注册APP
		f. 顶部 {% load tag %}
		g. {{ 参数1|函数名:"参数二" }}
		缺点:
			参数只能有一个,不能加空格
			优点:
			可以使用if
(2)配置tag.py
[root@python project1]# vim app/templatetags/tag.py
#!/usr/bin/env python
# coding:utf-8
from django import template
register = template.Library()
@register.simple_tag
def add(a, b):
    return a + b

@register.filter
def addFilter(a, b):
    return a + b
(2)配置HTML
[root@python project1]# vim templates/tpl2.html
{% load tag %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ name }}
    {{ name|lower }}
    {% add 2 3 %}
    {{  name|addFilter:"yayaya"  }}
    {% if "dream"|addFilter:"yayaya" == "dreamyayaya" %}
        bbbbb
    {% endif %}
</body>
</html>
(3)访问
http://10.10.10.111:8000/tpl2/

四、自定义分页


1、XSS攻击(跨站脚本攻击)

通过下面二种方式使传入字符串等能够正常显示,默认是有保护机制!!!

1、
	{{ page_str|safe }}
2、
	mark_safe(page_str)
(1)safe方式

<1> 配置urls.py

[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include

urlpatterns = [
    path('tpl/', views.tpl),
    path('tpl2/', views.tpl2),
    path('user/', views.user),
]

<2> 配置views.py

[root@python project1]# vim app/views.py       ###添加user函数
def user(request):
    current_page = request.GET.get('p', 1)
    start = (int(current_page) - 1) * 10
    stop = int(current_page) * 10
    li = []
    for i in range(100):
        li.append(i)
    data = li[start:stop]
    page_str = """
            <a href="/user/?p=1">1</a>
            <a href="/user/?p=2">2</a>
            <a href="/user/?p=3">3</a>
    """
    return render(request, 'user.html', {'li': data, 'page_str': page_str})

<3> 配置HTML

[root@python project1]# vim templates/user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        {% for i in li %}
            <li>{{ i }}</li>
        {% endfor%}
        {{ page_str|safe }}
    </ul>
</body>
</html>
http://10.10.10.111:8000/user/
(2)mark_safe方式

<1> 配置views.py

[root@python project1]# vim app/views.py
def user(request):
    from django.utils.safestring import mark_safe
    current_page = request.GET.get('p', 1)
    start = (int(current_page) - 1) * 10
    stop = int(current_page) * 10
    li = []
    for i in range(100):
        li.append(i)
    data = li[start:stop]
    page_str = """
            <a href="/user/?p=1">1</a>
            <a href="/user/?p=2">2</a>
            <a href="/user/?p=3">3</a>
    """
    page_str = mark_safe(page_str)
    return render(request, 'user.html', {'li': data, 'page_str': page_str})

<2> 配置HTML

[root@python project1]# vim templates/user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        {% for i in li %}
            <li>{{ i }}</li>
        {% endfor%}
        {{ page_str }}
    </ul>
</body>
</html>

<3> 访问

http://10.10.10.111:8000/user/

2、分页

这样的显示会有问题(数据多),当页数很多的时候会显示很多索引!!!

(1)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.utils.safestring import mark_safe
...
def user(request):
    from django.utils.safestring import mark_safe
    current_page = int(request.GET.get('p', 1))
    start = (current_page - 1) * 10
    end = current_page * 10
    li = []
    for i in range(109):
        li.append(i)
    data = li[start:end]
    num = len(li)
    count, remainder = divmod(num, 10)
    if remainder:
        count += 1
    page_list = []
    for k in range(1, count + 1):
        ### 判断加上active
        if k == current_page:
            str = '<a class="page active" href="/user/?p=%s">%s</a>' % (k, k)
        else:
            str = '<a class="page" href="/user/?p=%s">%s</a>' % (k, k)
        page_list.append(str)
    page_str = "".join(page_list)
    page_str = mark_safe(page_str)
    return render(request, 'user.html', {'li': data, 'page_str': page_str})
(2)配置HTML
[root@python project1]# vim templates/user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 3px;
            background-color: bisque;
            margin: 2px;
        }

        .pagination .page.active{
            background-color: deepskyblue;
            color: #00a65a;
        }
    </style>
</head>
<body>
    <ul>
        {% for i in li %}
            <li>{{ i }}</li>
        {% endfor%}
    </ul>
    <div class="pagination">
        {{ page_str }}
    </div>
</body>
</html>
(3)访问
http://10.10.10.111:8000/user/

3、分页优化

(1)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.utils.safestring import mark_safe
...
def user(request):
    current_page = int(request.GET.get('p', 1))
    ### 每页显示多少条数据和多少索引
    per_page_count = 10
    page_num = 11
    start = (current_page - 1) * per_page_count
    end = current_page * per_page_count
    li = []
    for i in range(1009):
        li.append(i)
    data = li[start:end]

    num = len(li)
    total_count, remainder = divmod(num, per_page_count)
    if remainder:
        total_count += 1
    page_list = []
    # start_index = current_page - 5
    # end_index = current_page + 5 + 1

    if total_count < page_num:
        start_index = 1
        end_index = total_count + 1
    else:
        if current_page <= (page_num + 1)/2:
            start_index = 1
            end_index = page_num + 1
        else:
            start_index = current_page - (page_num - 1)/2
            end_index = current_page + (page_num + 1)/2
            if (current_page + (page_num - 1)/2) > total_count:
                start_index = total_count - page_num + 1
                end_index = total_count + 1
    if current_page == 1:
        prev = '<a class="page active" href="#">上一页</a>'
    else:
        prev = '<a class="page active" href="/user/?p=%s">上一页</a>' % (current_page - 1)
    page_list.append(prev)
    for k in range(int(start_index), int(end_index)):
        ### 判断加上active
        if k == current_page:
            str = '<a class="page active" href="/user/?p=%s">%s</a>' % (k, k)
        else:
            str = '<a class="page" href="/user/?p=%s">%s</a>' % (k, k)
        page_list.append(str)
    if current_page == total_count:
        next_page = '<a class="page active" href="javascript:void(0);">下一页</a>'
    else:
        next_page = '<a class="page active" href="/user/?p=%s">下一页</a>' % (current_page + 1)
    page_list.append(next_page)
    jump = """
        <input type='text'/><a onclick='jumpTo(this,"/user/?p=");'>GO</a>
        <script>
            function jumpTo(ths, base){
                var v = ths.previousSibling.value;
                location.href = base + v;
            }
        </script>
    """
    page_list.append(jump)
    page_str = "".join(page_list)
    page_str = mark_safe(page_str)
    return render(request, 'user.html', {'li': data, 'page_str': page_str})
(2)访问
http://10.10.10.111:8000/user/

4、封装为类

(1)配置pagination.py
[root@python project1]# mkdir utils/
[root@python project1]# vim utils/pagination.py
#!/usr/bin/env python
# coding:utf-8
from django.utils.safestring import mark_safe

class Page:
    def __init__(self, current_page, data_count, per_page_count=10, page_num=7):
        self.current_page = current_page
        self.data_count = data_count
        self.per_page_count = per_page_count
        self.page_num = page_num

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count


    @property
    def total_count(self):
        x, y = divmod(self.data_count, self.per_page_count)
        if y:
            x += 1
        return x

    def page_str(self, base_url):
        page_list = []
        if self.total_count < self.page_num:
            start_index = 1
            end_index = self.total_count + 1
        else:
            if self.current_page <= (self.page_num + 1) / 2:
                start_index = 1
                end_index = self.page_num + 1
            else:
                start_index = self.current_page - (self.page_num - 1) / 2
                end_index = self.current_page + (self.page_num + 1) / 2
                if (self.current_page + (self.page_num - 1) / 2) > self.total_count:
                    start_index = self.total_count - self.page_num + 1
                    end_index = self.total_count + 1
        if self.current_page == 1:
            prev = '<a class="page active" href="#">上一页</a>'
        else:
            prev = '<a class="page active" href="/user/?p=%s">上一页</a>' % (self.current_page - 1)
        page_list.append(prev)
        for k in range(int(start_index), int(end_index)):
            ### 判断加上active
            if k == self.current_page:
                str = '<a class="page active" href="/user/?p=%s">%s</a>' % (k, k)
            else:
                str = '<a class="page" href="/user/?p=%s">%s</a>' % (k, k)
            page_list.append(str)
        if self.current_page == self.total_count:
            next_page = '<a class="page active" href="javascript:void(0);">下一页</a>'
        else:
            next_page = '<a class="page active" href="/user/?p=%s">下一页</a>' % (self.current_page + 1)
        page_list.append(next_page)
        jump = """
            <input type='text'/><a onclick='jumpTo(this,"%s?p=");'>GO</a>
            <script>
                function jumpTo(ths, base){
                    var v = ths.previousSibling.value;
                    location.href = base + v; 
                }
            </script>
        """ % (base_url,)
        page_list.append(jump)
        page_str = "".join(page_list)
        page_str = mark_safe(page_str)
        return page_str
(2)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from utils import pagination
...
def user(request):
    li = []
    for i in range(1009):
        li.append(i)
    current_page = int(request.GET.get('p', 1))
    page_obj = pagination.Page(current_page, len(li))
    data = li[page_obj.start:page_obj.end]
    page_str = page_obj.page_str('/user/')
    return render(request, 'user.html', {'li': data, 'page_str': page_str, })

五、Cookie操作


1、cookie登陆

(1)配置urls.py
[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include

urlpatterns = [
    path('tpl/', views.tpl),
    path('tpl2/', views.tpl2),
    path('user/', views.user),
    path('login/', views.login),
    path('index/', views.index),
]
(2)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
...
user_info = {
    'dream': {'pwd': '123'},
    'dreamya': {'pwd': '456'},
}

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request, 'login.html')
        if dic['pwd'] == p:
            res = redirect('/index/')
            ### 设置cookie,浏览器关闭后就会失效
            res.set_cookie('username111', u)
            return res
        else:
            return render(request, 'login.html')

def index(request):
    ### 获取当前用户
    v = request.COOKIES.get('username111')
    if not v:
        return redirect('/login/')
    else:
        return render(request, 'index.html', {'current_user': v})
(3)配置HTML

<1> 配置login.html

[root@python project1]# vim templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login/" method="POST">
    <input type="text" name="username" placeholder="用户名" />
    <input type="password" name="pwd" placeholder="密码" />
    <input type="submit" value="提交"/>
</form>
</body>
</html>

<2> 配置index.html

[root@python project1]# vim templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎登陆:{{ current_user }}</h1>
</body>
</html>

可以发现我们可以通过http://10.10.10.111:8000/index/直接进行登陆的话不会成功,只能通过http://10.10.10.111:8000/login/,但是我们登陆后就可以直接登陆!!!

2、cookie设置

(1)介绍
set_cookie('key', 'value')                      ###设置cookie
max_age:
	set_cookie('key', 'value',max_age=10)      ###10s后失效

expires:截止时间失效
	import datetime
	current_date = datetime.datetime.utcnow()
	current_date = current_date + datetime.timedelta(seconds=10)
	set_cookie('key', 'value',expires=current_date)    ###10s后消失
	
path='/',                  ###cookie生效的路径,/表示根路径,可以修改为指定路径
domain=None,               ###cookie生效的域名
secure=False,             ###https传输(True)
httponly=False,            ###js中不能直接获取(True),document.cookie

3、基于cookie设置显示数目

(1)插件下载

官网链接:http://plugins.jquery.com/cookie/
github下载链接:https://github.com/carhartl/jquery-cookie/releases

### 下载好放入static目录
[root@python ~]# wget https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js

注意:这样我们设置的cookie是全局的,我们可以加入path设置,从而设置为某个页面!!!

(2)配置views.py
[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
from utils import pagination
...
def user(request):
    li = []
    for i in range(1009):
        li.append(i)
    current_page = int(request.GET.get('p', 1))
    val = int(request.COOKIES.get('per_page_count'))
    page_obj = pagination.Page(current_page, len(li),val)
    data = li[page_obj.start:page_obj.end]
    page_str = page_obj.page_str('/user/')
    return render(request, 'user.html', {'li': data, 'page_str': page_str, })
(3)配置HTML
[root@python project1]# vim templates/user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .pagination .page{
            display: inline-block;
            padding: 3px;
            background-color: bisque;
            margin: 2px;
        }

        .pagination .page.active{
            background-color: deepskyblue;
            color: #00a65a;
        }
    </style>
</head>
<body>
    <ul>
        {% for i in li %}
            <li>{{ i }}</li>
        {% endfor%}
    </ul>
    <div>
        <select id="i1" onchange="changePageSize(this);">
            <option value="10">10</option>
            <option value="30">30</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>
    <div class="pagination">
        {{ page_str }}
    </div>
    <script src="/static/jquery-1.12.4.min.js"></script>
    <script src="/static/jquery.cookie-1.4.1.min.js"></script>
    <script>
        $(function () {
            var v = $.cookie('per_page_count');
            $('#i1').val(v);
        })
        function changePageSize(ths) {
            var v = $(ths).val();
            $.cookie('per_page_count',v);
            location.reload();
        }
    </script>
</body>
</html>
(4)访问
http://10.10.10.111:8000/user/

4、带签名的cookie

设置cookie为密文的!!!

obj = HttpResponse('s')
obj.set_signed_cookie('username', 'signCookie', salt='dreamya')
obj.get_signed_cookie('username', salt='dreamya')

六、FBV和CBV用户认证


1、FBV

[root@python project1]# vim app/views.py
def auth(func):
    def fun(request, *args, **kwargs):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return fun
@auth
def index(request):
    v = request.COOKIES.get('username111')
    return render(request, 'index.html', {'current_user': v})

2、CSV

(1)普通写法

<1> 配置urls.py

[root@python project1]# vim project1/urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.urls import include

urlpatterns = [
    path('tpl/', views.tpl),
    path('tpl2/', views.tpl2),
    path('user/', views.user),
    path('login/', views.login),
    path('index/', views.index),
    path('order/', views.Order.as_view()),
]

<2> 配置views.py

[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
def tpl(request):
    user_list = [1, 2, 3, 4]
    return render(request, 'tpl.html', {'user_list': user_list, })

def tpl2(request):
    return render(request, 'tpl2.html', {'name': "DREAMya"})

from utils import pagination

def user(request):
    li = []
    for i in range(1009):
        li.append(i)
    current_page = int(request.GET.get('p', 1))

    val = int(request.COOKIES.get('per_page_count'))
    print (val)
    page_obj = pagination.Page(current_page, len(li), val)
    data = li[page_obj.start:page_obj.end]
    page_str = page_obj.page_str('/user/')
    return render(request, 'user.html', {'li': data, 'page_str': page_str, })

user_info = {
    'dream': {'pwd': '123'},
    'dreamya': {'pwd': '456'},
}

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request, 'login.html')
        if dic['pwd'] == p:
            res = redirect('/index/')
            ### 设置cookie,浏览器关闭后就会失效
            res.set_cookie('username111', u)
            return res
        else:
            return render(request, 'login.html')

def auth(func):
    def fun(request, *args, **kwargs):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return fun
@auth
def index(request):
    v = request.COOKIES.get('username111')
    return render(request, 'index.html', {'current_user': v})

def cookie(request):
    obj = HttpResponse('s')
    obj.set_signed_cookie('username', 'signCookie', salt='dreamya')
    obj.get_signed_cookie('username', salt='dreamya')
    return render(request, 'index.html')

from django import views
class Order(views.View):
    def get(self,request):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/index')
        return render(request, 'index.html', {'current_user': v})
    def post(self,request):
        v = request.COOKIES.get('username111')
        return render(request,'index.html', {'current_user': v})

访问:http://10.10.10.111:8000/order/

(2)优化

<1> 介绍

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,request):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/index')
        return render(request, 'index.html', {'current_user': v})
    def post(self,request):
        v = request.COOKIES.get('username111')
        return render(request,'index.html', {'current_user': v})

<2> 配置views.py

[root@python project1]# vim app/views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.urls import reverse
from django.shortcuts import redirect
from django.utils.safestring import mark_safe
from utils import pagination
...
def user(request):
    li = []
    for i in range(1009):
        li.append(i)
    current_page = int(request.GET.get('p', 1))

    val = int(request.COOKIES.get('per_page_count'))
    print (val)
    page_obj = pagination.Page(current_page, len(li), val)
    data = li[page_obj.start:page_obj.end]
    page_str = page_obj.page_str('/user/')
    return render(request, 'user.html', {'li': data, 'page_str': page_str, })

user_info = {
    'dream': {'pwd': '123'},
    'dreamya': {'pwd': '456'},
}

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)
        if not dic:
            return render(request, 'login.html')
        if dic['pwd'] == p:
            res = redirect('/index/')
            ### 设置cookie,浏览器关闭后就会失效
            res.set_cookie('username111', u)
            return res
        else:
            return render(request, 'login.html')

def auth(func):
    def fun(request, *args, **kwargs):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return fun
    
@auth
def index(request):
    v = request.COOKIES.get('username111')
    return render(request, 'index.html', {'current_user': v})


def cookie(request):
    obj = HttpResponse('s')
    obj.set_signed_cookie('username', 'signCookie', salt='dreamya')
    obj.get_signed_cookie('username', salt='dreamya')
    return render(request, 'index.html')

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,request):
        v = request.COOKIES.get('username111')
        if not v:
            return redirect('/index')
        return render(request, 'index.html', {'current_user': v})
    def post(self,request):
        v = request.COOKIES.get('username111')
        return render(request,'index.html', {'current_user': v})

下一篇文章>Django入门(四)之Session操作、CSRF操作、自定义中间件、缓存、信号和Form组件

猜你喜欢

转载自blog.csdn.net/Dream_ya/article/details/86604828
今日推荐