首页 > 其他 > 详细

django-中间件

时间:2019-12-04 12:17:37      阅读:75      评论:0      收藏:0      [点我收藏+]

编写中间件类:
```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 = [
...
]
```
- 中间件的执行过程
- ![](images/middleware.jpeg)


- 练习
- 用中间件实现强制某个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) + ‘次,您被禁止了‘)
```

django-中间件

原文:https://www.cnblogs.com/chenlulu1122/p/11980739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!