def __init__(self, filename, flags=0, cache=True): """ Initialize the class. @param filename: Path to a geoip database. @type filename: str @param flags: Flags that affect how the database is processed. Currently supported flags are STANDARD (the default), MEMORY_CACHE (preload the whole file into memory) and MMAP_CACHE (access the file via mmap). @type flags: int @param cache: Used in tests to skip instance caching @type cache: bool """ self._lock = Lock() self._flags = flags self._netmask = None if self._flags & const.MMAP_CACHE and mmap is None: # pragma: no cover import warnings warnings.warn("MMAP_CACHE cannot be used without a mmap module") self._flags &= ~const.MMAP_CACHE if self._flags & const.MMAP_CACHE: f = codecs.open(filename, 'rb', ENCODING) access = mmap.ACCESS_READ self._fp = mmap.mmap(f.fileno(), 0, access=access) self._type = 'MMAP_CACHE' f.close() elif self._flags & const.MEMORY_CACHE: f = codecs.open(filename, 'rb', ENCODING) self._memory = f.read() self._fp = util.str2fp(self._memory) self._type = 'MEMORY_CACHE' f.close() else: self._fp = codecs.open(filename, 'rb', ENCODING) self._type = 'STANDARD' try: self._lock.acquire() self._setup_segments() finally: self._lock.release()
def __init__(self, filename='data/GeoIP.dat', flags=STANDARD, cache=True): """ Create and return an GeoIP instance. :arg filename: File path to a GeoIP database :arg flags: Flags that affect how the database is processed. Currently supported flags are STANDARD (default), MEMORY_CACHE (preload the whole file into memory) and MMAP_CACHE (access the file via mmap) :arg cache: Used in tests to skip instance caching """ self._lock = Lock() self._flags = flags self._netmask = None filename = resource_filename(__name__, filename) if self._flags & const.MMAP_CACHE and mmap is None: # pragma: no cover import warnings warnings.warn("MMAP_CACHE cannot be used without a mmap module") self._flags &= ~const.MMAP_CACHE if self._flags & const.MMAP_CACHE: f = codecs.open(filename, 'rb', ENCODING) access = mmap.ACCESS_READ self._fp = mmap.mmap(f.fileno(), 0, access=access) self._type = 'MMAP_CACHE' f.close() elif self._flags & const.MEMORY_CACHE: f = codecs.open(filename, 'rb', ENCODING) self._memory = f.read() self._fp = util.str2fp(self._memory) self._type = 'MEMORY_CACHE' f.close() else: self._fp = codecs.open(filename, 'rb', ENCODING) self._type = 'STANDARD' try: self._lock.acquire() self._setup_segments() finally: self._lock.release()