当前位置: 首页 > 文档资料 > Python 全栈 >

①. 添加中间件

优质
小牛编辑
137浏览
2023-12-01
  • 此中间件对后台网址访问做了是否登录的判断
  • 关于网站后台要求:只要访问的URL地址是以 "/admin" 开头的都会执行是否登录判断验证。

(1). 在common公共应用中创建中间件

  • 创建文件: myobject/common/shopmiddleware.py, 代码如下:
# 自定义中间件类
from django.shortcuts import redirect
from django.core.urlresolvers import reverse

import re

class ShopMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization(一次性配置和初始化).
        #print("ShopMiddleware")

    def __call__(self, request):
        # 定义网站后台不用登录也可访问的路由url
        urllist = ['/myadmin/login','/myadmin/dologin','/myadmin/logout']
        # 获取当前请求路径
        path = request.path
        #print("Hello World!"+path)
        # 判断当前请求是否是访问网站后台,并且path不在urllist中
        if re.match("/myadmin",path) and (path not in urllist):
            # 判断当前用户是否没有登录
            if "adminuser" not in request.session:
                # 执行登录界面跳转
                return redirect(reverse('myadmin_login'))


        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

(2). 将自定义的中间件注册到项目中

  • 编辑 myobject/settings.py 配置文件, 添加如下代码
...

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'common.shopmiddleware.ShopMiddleware',     #注册中间件
]

...

(3). 配置路由、模板并测试中间件

  • 3.1 配置路由 myobject/myadmin/urls.py 加入如下代码
 ....

    # 后台管理员路由
    url(r'^login$', index.login, name="myadmin_login"),
    url(r'^dologin$', index.dologin, name="myadmin_dologin"),
    url(r'^logout$', index.logout, name="myadmin_logout"),
 ....
  • 3.2 编写视图 myobject/myadmin/views/index.py文件 并加入如下代码:
...
# ==============后台管理员操作====================
# 会员登录表单
def login(request):
    return render(request,'myadmin/login.html')

# 会员执行登录
def dologin(request):
    pass

# 会员退出
def logout(request):
    pass
...
  • 3.3 创建登录模板文件: templates/myadmin/login.html 代码如下:
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="cn">
    <head>
        <meta charset="utf-8">
        <title>Login - Akira</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="{% static 'myadmin/css/bootstrap.min.css' %}" rel="stylesheet">
        <link href="{% static 'myadmin/css/bootstrap-responsive.min.css' %}" rel="stylesheet">
        <link href="{% static 'myadmin/css/site.css' %}" rel="stylesheet">
        <!--[if lt IE 9]><script src="{% static 'myadmin/js/html5.js' %}"></script><![endif]-->
    </head>
    <body>
        <div id="login-page" class="container">
            <h1>商城后台管理登录</h1>
            <form id="login-form" method="post" class="well" action="{% url 'myadmin_dologin' %}">
            {% csrf_token %}
            账号:<input type="text" name="username" class="span2" placeholder="输入账号" /><br />
            密码:<input type="password" name="password" class="span2" placeholder="输入密码" /><br />
            <label class="checkbox"> <input type="checkbox" /> Remember me </label>
            <button type="submit" class="btn btn-primary">登录</button>
            <button type="reset" class="btn">重置</button>
        </form> 
        <br/>
        <span style="color:red">{{ info }}</span>
        </div>
        <script src="{% static 'myadmin/js/jquery.min.js' %}"></script>
        <script src="{% static 'myadmin/js/bootstrap.min.js' %}"></script>
        <script src="{% static 'myadmin/js/site.js' %}"></script>
    </body>
</html>

4. 启动服务测试,网站后台就进不去了,统一调跳转登录页面中