Skip to content

Commit bc7c5e8

Browse files
committed
Set an explicit user-agent for the Python API
1 parent 254a285 commit bc7c5e8

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

geoip2/webservices.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,11 @@
9393
check to see if the attribute is set.
9494
9595
"""
96+
97+
import geoip2
9698
import geoip2.models
9799
import requests
100+
from requests.utils import default_user_agent
98101
from .errors import GeoIP2Error, GeoIP2HTTPError, GeoIP2WebServiceError
99102

100103

@@ -202,13 +205,18 @@ def omni(self, ip_address='me'):
202205
def _response_for(self, path, model_class, ip_address):
203206
uri = '/'.join([self._base_uri, path, ip_address])
204207
response = requests.get(uri, auth=(self.user_id, self.license_key),
205-
headers={'Accept': 'application/json'})
208+
headers={'Accept': 'application/json',
209+
'User-Agent': self._user_agent() })
206210
if (response.status_code == 200):
207211
body = self._handle_success(response, uri)
208212
return model_class(body, languages=self.languages)
209213
else:
210214
self._handle_error(response, uri)
211215

216+
def _user_agent(self):
217+
return 'GeoIP2 Python Client v%s (%s)' % (geoip2.__version__,
218+
default_user_agent())
219+
212220
def _handle_success(self, response, uri):
213221
try:
214222
return response.json()

tests/webservices_test.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222

2323
if sys.version_info[0] == 2:
2424
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
25+
unittest.TestCase.assertRegex = unittest.TestCase.assertRegexpMatches
26+
2527

2628

2729
@patch.object(requests, 'get')
@@ -163,10 +165,17 @@ def test_300_error(self, get):
163165
def test_request(self, get):
164166
self._setup_get(get, 'country', 200, self.country)
165167
country = self.client.country('1.2.3.4')
166-
get.assert_called_with('https://geoip.maxmind.com'
167-
'/geoip/v2.0/country/1.2.3.4',
168-
headers={'Accept': 'application/json'},
169-
auth=(42, 'abcdef123456'))
168+
args, kwargs = get.call_args
169+
self.assertEqual(args[0], 'https://geoip.maxmind.com'
170+
'/geoip/v2.0/country/1.2.3.4',
171+
'correct URI is used')
172+
self.assertEqual(kwargs.get('headers').get('Accept'),
173+
'application/json',
174+
'correct Accept header')
175+
self.assertRegex(kwargs.get('headers').get('User-Agent'),
176+
'^GeoIP2 Python Client v',
177+
'Correct User-Agent')
178+
self.assertEqual(kwargs.get('auth'), (42, 'abcdef123456'))
170179

171180
def test_city_ok(self, get):
172181
self._setup_get(get, 'city', 200, self.country)

0 commit comments

Comments
 (0)