Skip to content

Commit f591515

Browse files
authored
Merge pull request #79 from ipinfo/custom_headers
allow custom headers
2 parents e6376dd + 63a74a8 commit f591515

File tree

6 files changed

+32
-13
lines changed

6 files changed

+32
-13
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,14 @@ Request behavior can be modified by setting the `request_options` keyword argume
230230
>>> handler = ipinfo.getHandler(request_options={'timeout': 4})
231231
```
232232

233+
### Custom Headers
234+
235+
You can add custom headers or modify default headers by setting the `headers` keyword argument when initializing the handler. `headers` is a dictionary of `{'header': 'value'}` format.
236+
237+
```python
238+
>>> handler = ipinfo.getHandler(headers={'user-agent': 'My Custom User-agent', 'custom_header': 'yes'})
239+
```
240+
233241
### Internationalization
234242

235243
When looking up an IP address, the response object includes a `details.country_name`, `details.isEU`, `details.country_flag` and `details.country_currency` attributes which includes the country based on American English. It is possible to return the country name in other languages by setting the `countries_file`, remove or add EU countries by setting the keyword argument `eu_countries_file`, change the country flag emoji or unicode by setting the keyword argument `countries_flags_file` or change country's currency code or currency symbol by setting the `countries_currencies` when creating the `IPinfo` object. Moreover the response object includes a `details.continent` which includes continent code and name of IP. The default file can be changed by setting the `continent_file` while creating the `IPinfo` object.

ipinfo/handler.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,9 @@ def __init__(self, access_token=None, **kwargs):
9595
cache_options["ttl"] = CACHE_TTL
9696
self.cache = DefaultCache(**cache_options)
9797

98+
# setup custom headers
99+
self.headers = kwargs.get("headers", None)
100+
98101
def getDetails(self, ip_address=None, timeout=None):
99102
"""
100103
Get details for specified IP address as a Details object.
@@ -133,7 +136,7 @@ def getDetails(self, ip_address=None, timeout=None):
133136
url = API_URL
134137
if ip_address:
135138
url += "/" + ip_address
136-
headers = handler_utils.get_headers(self.access_token)
139+
headers = handler_utils.get_headers(self.access_token, self.headers)
137140
response = requests.get(url, headers=headers, **req_opts)
138141
if response.status_code == 429:
139142
raise RequestQuotaExceededError()
@@ -226,7 +229,7 @@ def getBatchDetails(
226229

227230
# loop over batch chunks and do lookup for each.
228231
url = API_URL + "/batch"
229-
headers = handler_utils.get_headers(self.access_token)
232+
headers = handler_utils.get_headers(self.access_token, self.headers)
230233
headers["content-type"] = "application/json"
231234
for i in range(0, len(lookup_addresses), batch_size):
232235
# quit if total timeout is reached.
@@ -295,7 +298,7 @@ def getMap(self, ips):
295298

296299
req_opts = {**self.request_options}
297300
url = f"{API_URL}/map?cli=1"
298-
headers = handler_utils.get_headers(None)
301+
headers = handler_utils.get_headers(None, self.headers)
299302
headers["content-type"] = "application/json"
300303
response = requests.post(
301304
url, json=ip_strs, headers=headers, **req_opts

ipinfo/handler_async.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ def __init__(self, access_token=None, **kwargs):
9898
if "ttl" not in cache_options:
9999
cache_options["ttl"] = CACHE_TTL
100100
self.cache = DefaultCache(**cache_options)
101-
101+
102+
# setup custom headers
103+
self.headers = kwargs.get("headers", None)
104+
102105
async def init(self):
103106
"""
104107
Initializes internal aiohttp connection pool.
@@ -153,7 +156,7 @@ async def getDetails(self, ip_address=None, timeout=None):
153156
url = API_URL
154157
if ip_address:
155158
url += "/" + ip_address
156-
headers = handler_utils.get_headers(self.access_token)
159+
headers = handler_utils.get_headers(self.access_token, self.headers)
157160
req_opts = {}
158161
if timeout is not None:
159162
req_opts["timeout"] = timeout
@@ -251,7 +254,7 @@ async def getBatchDetails(
251254

252255
# loop over batch chunks and prepare coroutines for each.
253256
url = API_URL + "/batch"
254-
headers = handler_utils.get_headers(self.access_token)
257+
headers = handler_utils.get_headers(self.access_token, self.headers)
255258
headers["content-type"] = "application/json"
256259

257260
# prepare coroutines that will make reqs and update results.

ipinfo/handler_utils.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,18 @@
4444
BATCH_REQ_TIMEOUT_DEFAULT = 5
4545

4646

47-
def get_headers(access_token):
47+
def get_headers(access_token, custom_headers):
4848
"""Build headers for request to IPinfo API."""
4949
headers = {
50-
"user-agent": "IPinfoClient/Python{version}/{sdk_version}".format(
51-
version=sys.version_info[0], sdk_version=SDK_VERSION
50+
"user-agent": "IPinfoClient/Python{version}/{sdk_version}".format(
51+
version=sys.version_info[0], sdk_version=SDK_VERSION
5252
),
5353
"accept": "application/json",
5454
}
5555

56+
if custom_headers:
57+
headers = {** headers, ** custom_headers}
58+
5659
if access_token:
5760
headers["authorization"] = "Bearer {}".format(access_token)
5861

tests/handler_async_test.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,14 @@ async def test_init():
2121
@pytest.mark.asyncio
2222
async def test_headers():
2323
token = "mytesttoken"
24-
handler = AsyncHandler(token)
25-
headers = handler_utils.get_headers(token)
24+
handler = AsyncHandler(token, headers={"custom_field": "yes"})
25+
headers = handler_utils.get_headers(token, handler.headers)
2626
await handler.deinit()
2727

2828
assert "user-agent" in headers
2929
assert "accept" in headers
3030
assert "authorization" in headers
31+
assert "custom_field" in headers
3132

3233

3334
@pytest.mark.asyncio

tests/handler_test.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,13 @@ def test_init():
2020

2121
def test_headers():
2222
token = "mytesttoken"
23-
handler = Handler(token)
24-
headers = handler_utils.get_headers(token)
23+
handler = Handler(token, headers={"custom_field": "yes"})
24+
headers = handler_utils.get_headers(token, handler.headers)
2525

2626
assert "user-agent" in headers
2727
assert "accept" in headers
2828
assert "authorization" in headers
29+
assert "custom_field" in headers
2930

3031

3132
def test_get_details():

0 commit comments

Comments
 (0)