File: database.py

package info (click to toggle)
python-geoip2 2.9.0%2Bdfsg1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 572 kB
  • sloc: python: 1,224; makefile: 5
file content (214 lines) | stat: -rw-r--r-- 7,618 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""
======================
GeoIP2 Database Reader
======================

"""
import inspect

import maxminddb
# pylint: disable=unused-import
from maxminddb import (MODE_AUTO, MODE_MMAP, MODE_MMAP_EXT, MODE_FILE,
                       MODE_MEMORY, MODE_FD)

import geoip2
import geoip2.models
import geoip2.errors


class Reader(object):
    """GeoIP2 database Reader object.

    Instances of this class provide a reader for the GeoIP2 database format.
    IP addresses can be looked up using the ``country`` and ``city`` methods.

    The basic API for this class is the same for every database. First, you
    create a reader object, specifying a file name or file descriptor.
    You then call the method corresponding to the specific database, passing
    it the IP address you want to look up.

    If the request succeeds, the method call will return a model class for the
    method you called. This model in turn contains multiple record classes,
    each of which represents part of the data returned by the database. If the
    database does not contain the requested information, the attributes on the
    record class will have a ``None`` value.

    If the address is not in the database, an
    ``geoip2.errors.AddressNotFoundError`` exception will be thrown. If the
    database is corrupt or invalid, a ``maxminddb.InvalidDatabaseError`` will
    be thrown.

"""

    def __init__(self, fileish, locales=None, mode=MODE_AUTO):
        """Create GeoIP2 Reader.

        :param fileish: The string path to the GeoIP2 database, or an existing
          file descriptor pointing to the database. Note that this latter
          usage is only valid when mode is MODE_FD.
        :param locales: This is list of locale codes. This argument will be
          passed on to record classes to use when their name properties are
          called. The default value is ['en'].

          The order of the locales is significant. When a record class has
          multiple names (country, city, etc.), its name property will return
          the name in the first locale that has one.

          Note that the only locale which is always present in the GeoIP2
          data is "en". If you do not include this locale, the name property
          may end up returning None even when the record has an English name.

          Currently, the valid locale codes are:

          * de -- German
          * en -- English names may still include accented characters if that
            is the accepted spelling in English. In other words, English does
            not mean ASCII.
          * es -- Spanish
          * fr -- French
          * ja -- Japanese
          * pt-BR -- Brazilian Portuguese
          * ru -- Russian
          * zh-CN -- Simplified Chinese.
        :param mode: The mode to open the database with. Valid mode are:
          * MODE_MMAP_EXT - use the C extension with memory map.
          * MODE_MMAP - read from memory map. Pure Python.
          * MODE_FILE - read database as standard file. Pure Python.
          * MODE_MEMORY - load database into memory. Pure Python.
          * MODE_FD - the param passed via fileish is a file descriptor, not a
             path. This mode implies MODE_MEMORY. Pure Python.
          * MODE_AUTO - try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order.
             Default.

        """
        if locales is None:
            locales = ['en']
        self._db_reader = maxminddb.open_database(fileish, mode)
        self._locales = locales

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

    def country(self, ip_address):
        """Get the Country object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.Country` object

        """

        return self._model_for(geoip2.models.Country, 'Country', ip_address)

    def city(self, ip_address):
        """Get the City object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.City` object

        """
        return self._model_for(geoip2.models.City, 'City', ip_address)

    def anonymous_ip(self, ip_address):
        """Get the AnonymousIP object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.AnonymousIP` object

        """
        return self._flat_model_for(geoip2.models.AnonymousIP,
                                    'GeoIP2-Anonymous-IP', ip_address)

    def asn(self, ip_address):
        """Get the ASN object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.ASN` object

        """
        return self._flat_model_for(geoip2.models.ASN, 'GeoLite2-ASN',
                                    ip_address)

    def connection_type(self, ip_address):
        """Get the ConnectionType object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.ConnectionType` object

        """
        return self._flat_model_for(geoip2.models.ConnectionType,
                                    'GeoIP2-Connection-Type', ip_address)

    def domain(self, ip_address):
        """Get the Domain object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.Domain` object

        """
        return self._flat_model_for(geoip2.models.Domain, 'GeoIP2-Domain',
                                    ip_address)

    def enterprise(self, ip_address):
        """Get the Enterprise object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.Enterprise` object

        """
        return self._model_for(geoip2.models.Enterprise, 'Enterprise',
                               ip_address)

    def isp(self, ip_address):
        """Get the ISP object for the IP address.

        :param ip_address: IPv4 or IPv6 address as a string.

        :returns: :py:class:`geoip2.models.ISP` object

        """
        return self._flat_model_for(geoip2.models.ISP, 'GeoIP2-ISP',
                                    ip_address)

    def _get(self, database_type, ip_address):
        if database_type not in self.metadata().database_type:
            caller = inspect.stack()[2][3]
            raise TypeError("The %s method cannot be used with the "
                            "%s database" % (caller,
                                             self.metadata().database_type))
        record = self._db_reader.get(ip_address)
        if record is None:
            raise geoip2.errors.AddressNotFoundError(
                "The address %s is not in the database." % ip_address)
        return record

    def _model_for(self, model_class, types, ip_address):
        record = self._get(types, ip_address)
        record.setdefault('traits', {})['ip_address'] = ip_address
        return model_class(record, locales=self._locales)

    def _flat_model_for(self, model_class, types, ip_address):
        record = self._get(types, ip_address)
        record['ip_address'] = ip_address
        return model_class(record)

    def metadata(self):
        """The metadata for the open database.

        :returns: :py:class:`maxminddb.reader.Metadata` object
        """
        return self._db_reader.metadata()

    def close(self):
        """Closes the GeoIP2 database."""

        self._db_reader.close()