Home > Article > Backend Development > Code example of Django middleware implementing user authentication and IP frequency limitation
The content of this article is about the code examples of Django middleware to implement user authentication and IP frequency limitation. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. URL access filtering
User authentication through decorators is very convenient, but when adding some functions that require authentication, you need to add decorations again If it is implemented through middleware, there is no need to add it.
import re LOGIN_URL = '/login/' class MyLogin(MiddlewareMixin): def process_request(self, request): # 获取当前页面的路由 url = request.get_full_path() path = request.path print(path) # 通过session判断是否登录 is_login = request.session.get('is_login') # 判断当前页面是否是login页面 if not re.match(path, LOGIN_URL): if not is_login: # 如果没有登录,重定向到login页面 return redirect('/login/?next=%s' % url) def process_response(self, request, response): return response
2. Limit IP access frequency
In order to prevent certain IP malicious For high-frequency access to the server, these IPs can be restricted and intercepted.
import time class OverTime(MiddlewareMixin): def process_request(self, request): # 获取客户端IP地址 IP = request.META.get('REMOTE_ADDR') # 获取该IP地址的值,如果没有,给一个默认列表[] lis = request.session.get(IP, []) # 获取当前时间 curr_time = time.time() # 判断操作次数是否小于3次 if len(lis) < 3: # 如果小于3次,添加本次操作时间 lis.append(curr_time) # 保存 request.session[IP] = lis else: # 如果本次操作时间减去第一次操作时间小于60秒,则不让其继续操作 if time.time() - lis[0] < 60: return HttpResponse('操作过于频繁') else: # 如果大于60秒则交叉复制 lis[0], lis[1], lis[2] = lis[1], lis[2], time.time() # 保存 request.session[IP] = lis def process_response(self, request, response): return response
The above is the detailed content of Code example of Django middleware implementing user authentication and IP frequency limitation. For more information, please follow other related articles on the PHP Chinese website!