dingxin_toolbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
739 B

from django.utils.deprecation import MiddlewareMixin
class SetRemoteAddrFromForwardedFor(MiddlewareMixin):
"""
如果部署了代理,使用此中间件获取远程客户端IP。
在settings中注册该中间件。
"""
def process_request(self, request):
# print('process_request')
# print("request.META")
# print(request.META)
try:
# print("request.META")
real_ip = request.META['HTTP_X_FORWARDED_FOR']
# print('real_ip', real_ip)
except KeyError as err:
print('HTTP_X_FORWARDED_FOR key error')
print(err)
else:
real_ip = real_ip.split(",")[0]
request.META['REMOTE_ADDR'] = real_ip