django 设置中间件(middleware),禁止某些用户访问站点

2023-02-18 10:38:36 浏览数 (1)

想要实现 IP 或者 用户 黑名单(小黑屋)功能,需要用到 django 的 middleware。

# 环境

1. django 1.11.x

2. python 3.6.x

# 步骤

1. blog (app 名称) 下新建 中间件 middleware.py

代码语言:javascript复制
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'yinzhuoqun'

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from blog.models import UserIP  # 用户访问的 IP 记录
from logger.logger import logger


class BlockVisit(MiddlewareMixin):
    def process_request(self, request):
        # values_list 如果只传递一个字段,你还可以传递flat 参数。如果为True,它表示返回的结果为单个值而不是元组。
        blcok_ip = UserIP.objects.filter(is_deleted=True).values_list("ip", flat=True)
        logger.debug(blcok_ip)
        logger.debug(request.META['REMOTE_ADDR'])
        if request.META['REMOTE_ADDR'] in blcok_ip:
            return HttpResponse(
                '<h1>对不起, 您被关小黑屋了!</h1><h4>如有疑问请邮箱联系:<a href="mailto:name@email.com">admin@xieboke.net</a></h4>'
                '<h1>Sorry,Your access is restricted!</h1>'
                '<h4>If you have any questions, please contact us by email:<a href="mailto:name@email.com">admin@xieboke.net</a></h4>')

    def process_response(self, request, response):
        return response

2. settings.py 中的 MIDDLEWARE_CLASSES 注册 BlockVisit,BlockVisit 要放在最前面

代码语言:javascript复制
MIDDLEWARE_CLASSES = (
    'blog.middleware.BlockVisit',  # 注册 BlockVisit 中间件,放最前面
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

0 人点赞