Skip to content

Commit

Permalink
Merge pull request #5 from lepture/no-mmap
Browse files Browse the repository at this point in the history
Use without mmap
  • Loading branch information
lxyu committed Oct 11, 2014
2 parents a148e48 + 2939ed1 commit 46e63be
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
17 changes: 13 additions & 4 deletions IP/ip.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# -*- coding: utf-8 -*-

import os
import mmap
import socket
import struct
try:
import mmap
except ImportError:
mmap = None

__all__ = ['IPv4Database', 'find']

Expand Down Expand Up @@ -35,12 +38,17 @@ class IPv4Database(object):
| data storage |
-----------------------
"""
def __init__(self, filename=None):
def __init__(self, filename=None, use_mmap=True):
if filename is None:
filename = datfile
with open(filename, 'rb') as f:
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if use_mmap and mmap is not None:
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
else:
buf = f.read()
use_mmap = False

self._use_mmap = use_mmap
self._buf = buf

self._offset = _unpack_N(buf[:4])
Expand All @@ -53,7 +61,8 @@ def __exit__(self, type, value, traceback):
self.close()

def close(self):
self._buf.close()
if self._use_mmap:
self._buf.close()
self._is_closed = True

def _lookup_ipv4(self, ip):
Expand Down
5 changes: 5 additions & 0 deletions test_ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ def test_ip():
def test_domain():
assert IP.find("localhost") == u("本机地址\t本机地址")
assert IP.find("ele.me") == u("中国\t北京\t北京")


def test_without_mmap():
with IP.IPv4Database(use_mmap=False) as db:
assert db.find("127.0.0.1") == u("本机地址\t本机地址")

0 comments on commit 46e63be

Please sign in to comment.