diff --git a/dingxin_toolbox_drf/http.py b/dingxin_toolbox_drf/http.py new file mode 100644 index 0000000..b904ad3 --- /dev/null +++ b/dingxin_toolbox_drf/http.py @@ -0,0 +1,16 @@ +from django.utils.deprecation import MiddlewareMixin + + +class SetRemoteAddrFromForwardedFor(MiddlewareMixin): + """ + 如果部署了代理,使用此中间件获取远程客户端IP。 + 在settings中注册该中间件。 + """ + + def process_request(self, request): + try: + real_ip = request.META['HTTP_X_FORWARDED_FOR'] + except KeyError as err: + print(err) + else: + real_ip = real_ip.split(",")[0] diff --git a/dingxin_toolbox_drf/settings.py b/dingxin_toolbox_drf/settings.py index e6384eb..af70d99 100644 --- a/dingxin_toolbox_drf/settings.py +++ b/dingxin_toolbox_drf/settings.py @@ -91,6 +91,7 @@ MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'dingxin_toolbox_drf.http.SetRemoteAddrFromForwardedFor', ] ROOT_URLCONF = 'dingxin_toolbox_drf.urls'