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)