Skip to content

Commit f712983

Browse files
committed
Merge pull request #29 from hongquan/master
Add context manager support
2 parents 4535268 + 371cdb5 commit f712983

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

geoip2/database.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,12 @@ def __init__(self, filename, locales=None, mode=MODE_AUTO):
8383
self._db_reader = maxminddb.open_database(filename, mode)
8484
self._locales = locales
8585

86+
def __enter__(self):
87+
return self
88+
89+
def __exit__(self, exc_type, exc_value, traceback):
90+
self.close()
91+
8692
def country(self, ip_address):
8793
"""Get the Country object for the IP address
8894

tests/database_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,12 @@ def test_isp(self):
149149

150150
reader.close()
151151

152+
def test_context_manager(self):
153+
with geoip2.database.Reader(
154+
'tests/data/test-data/GeoIP2-Country-Test.mmdb') as reader:
155+
record = reader.country('81.2.69.160')
156+
self.assertEqual(record.traits.ip_address, '81.2.69.160')
157+
152158

153159
@unittest.skipUnless(maxminddb.extension, 'No C extension module found. Skipping tests')
154160
class TestExtensionReader(BaseTestReader, unittest.TestCase):

0 commit comments

Comments
 (0)