编写中间件类:
```python
1.创建 file : middleware/mymiddleware.py
2.
from django.http import HttpResponse, Http404
from django.utils.deprecation import MiddlewareMixin
class MyMiddleWare(MiddlewareMixin):
    def process_request(self, request):
        print("中间件方法 process_request 被调用")
    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("中间件方法 process_view 被调用")
    def process_response(self, request, response):
        print("中间件方法 process_response 被调用")
        return response
    def process_exception(self, request, exception):
        print("中间件方法 process_exception 被调用")
    def process_template_response(self, request, response):
        print("中间件方法 process_template_response 被调用")
        return response
```
3.注册中间件:
```python
# file : settings.py
MIDDLEWARE = [
    ...
       ]
```
- 中间件的执行过程
    - 
- 练习
    - 用中间件实现强制某个IP地址只能向/test 发送 5 次GET请求
    - 提示:
        - request.META[‘REMOTE_ADDR‘] 可以得到远程客户端的IP地址
        - request.path_info 可以得到客户端访问的GET请求路由信息
    - 答案:
        ```python
        from django.http import HttpResponse, Http404
        from django.utils.deprecation import MiddlewareMixin
        import re
        class VisitLimit(MiddlewareMixin):
            ‘‘‘此中间件限制一个IP地址对应的访问/user/login 的次数不能改过10次,超过后禁止使用‘‘‘
            visit_times = {}  # 此字典用于记录客户端IP地址有访问次数
            def process_request(self, request):
                ip_address = request.META[‘REMOTE_ADDR‘]  # 得到IP地址
                if not re.match(‘^/test$‘, request.path_info):
                    return
                times = self.visit_times.get(ip_address, 0)
                self.visit_times[ip_address] = times + 1
                if times < 5:
                    return
                return HttpResponse(‘你已经访问过‘ + str(times) + ‘次,您被禁止了‘)
        ```
原文:https://www.cnblogs.com/chenlulu1122/p/11980739.html