From 39f2aabdd346a77e9b691b13b01244156eb4a773 Mon Sep 17 00:00:00 2001 From: Oleg Marshev Date: Fri, 27 Jun 2014 14:53:58 +0300 Subject: [PATCH] Do not look for country if no new ip. --- common/djangoapps/geoinfo/middleware.py | 5 ++++- common/djangoapps/geoinfo/tests/test_middleware.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/common/djangoapps/geoinfo/middleware.py b/common/djangoapps/geoinfo/middleware.py index a6ff5289de..4779b2f63a 100644 --- a/common/djangoapps/geoinfo/middleware.py +++ b/common/djangoapps/geoinfo/middleware.py @@ -32,7 +32,10 @@ class CountryMiddleware(object): new_ip_address = get_real_ip(request) old_ip_address = request.session.get('ip_address', None) - if new_ip_address != old_ip_address: + if not new_ip_address and old_ip_address: + del request.session['ip_address'] + del request.session['country_code'] + elif new_ip_address != old_ip_address: country_code = pygeoip.GeoIP(settings.GEOIP_PATH).country_code_by_addr(new_ip_address) request.session['country_code'] = country_code request.session['ip_address'] = new_ip_address diff --git a/common/djangoapps/geoinfo/tests/test_middleware.py b/common/djangoapps/geoinfo/tests/test_middleware.py index 3d90c76faa..05982fb98c 100644 --- a/common/djangoapps/geoinfo/tests/test_middleware.py +++ b/common/djangoapps/geoinfo/tests/test_middleware.py @@ -92,3 +92,17 @@ class CountryMiddlewareTests(TestCase): # Country code is not changed. self.assertEqual('CN', request.session.get('country_code')) self.assertEqual('117.79.83.100', request.session.get('ip_address')) + + def test_ip_address_is_none(self): + # IP address is not defined in request. + request = self.request_factory.get('/somewhere') + request.user = self.anonymous_user + # Run process_request to set up the session in the request + # to be able to override it. + self.session_middleware.process_request(request) + request.session['country_code'] = 'CN' + request.session['ip_address'] = '117.79.83.1' + self.country_middleware.process_request(request) + # No country code exists after request processing. + self.assertNotIn('country_code', request.session) + self.assertNotIn('ip_address', request.session)