Skip to content

Commit 7a04ad4

Browse files
committed
allow custom ip lookup function
1 parent baeec4d commit 7a04ad4

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/flask_track_usage/__init__.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ class TrackUsage(object):
5656
Tracks basic usage of Flask applications.
5757
"""
5858

59-
def __init__(self, app=None, storage=None, _fake_time=None):
59+
def __init__(self, app=None, storage=None, ip_lookup_func=None, _fake_time=None):
6060
"""
6161
Create the instance.
6262
@@ -78,9 +78,9 @@ def __init__(self, app=None, storage=None, _fake_time=None):
7878
self._fake_time = _fake_time
7979

8080
if app is not None and storage is not None:
81-
self.init_app(app, storage)
81+
self.init_app(app, storage, ip_lookup_func)
8282

83-
def init_app(self, app, storage):
83+
def init_app(self, app, storage, ip_lookup_func):
8484
"""
8585
Initialize the instance with the app.
8686
@@ -90,6 +90,7 @@ def init_app(self, app, storage):
9090
"""
9191
self.app = app
9292
self._storages = storage
93+
self.ip_lookup_func = ip_lookup_func
9394
self._use_freegeoip = app.config.get(
9495
'TRACK_USAGE_USE_FREEGEOIP', False)
9596
self._freegeoip_endpoint = app.config.get(
@@ -190,7 +191,10 @@ def after_request(self, response):
190191
data['username'] = str(ctx.request.authorization.username)
191192
elif getattr(self.app, 'login_manager', None) and current_user and not current_user.is_anonymous:
192193
data['username'] = str(current_user)
193-
if self._use_freegeoip:
194+
if self.ip_lookup_func:
195+
clean_ip = quote_plus(str(ctx.request.remote_addr))
196+
data['ip_info'] = self.ip_lookup_func(clean_ip)
197+
elif self._use_freegeoip:
194198
clean_ip = quote_plus(str(ctx.request.remote_addr))
195199
if '{ip}' in self._freegeoip_endpoint:
196200
url = self._freegeoip_endpoint.format(ip=clean_ip)

0 commit comments

Comments
 (0)