Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use without mmap #5

Merged
merged 1 commit into from
Oct 11, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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本机地址")