当前位置: 首页>>代码示例>>Python>>正文


Python geoip2.GeoIP2方法代码示例

本文整理汇总了Python中django.contrib.gis.geoip2.GeoIP2方法的典型用法代码示例。如果您正苦于以下问题:Python geoip2.GeoIP2方法的具体用法?Python geoip2.GeoIP2怎么用?Python geoip2.GeoIP2使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.contrib.gis.geoip2的用法示例。


在下文中一共展示了geoip2.GeoIP2方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: detect_geo

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def detect_geo(self):
        if self.ip and self.counter == 0:
            try:
                # Django 1.9+
                from django.contrib.gis.geoip2 import GeoIP2 as GeoIP
                from django.contrib.gis.geoip2 import GeoIP2Exception \
                    as GeoIPException
            except ImportError:
                # Django 1.8
                from django.contrib.gis.geoip import GeoIP
                from django.contrib.gis.geoip import GeoIPException

            try:
                g = GeoIP()
                info = g.city(self.ip) or dict()
                for (k, v) in info.items():
                    setattr(self, 'ip_%s' % k, v)
            except GeoIPException:
                pass 
开发者ID:LPgenerator,项目名称:django-db-mailer,代码行数:21,代码来源:models.py

示例2: __call__

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def __call__(self, request):
        if "HTTP_X_FORWARDED_FOR" in request.META:
            request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
            parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1)
            request.META["REMOTE_ADDR"] = parts[0]
        ip = request.META["REMOTE_ADDR"]
        g = GeoIP2()
        try:
            ip_response = g.city(ip)
            time_zone = ip_response['time_zone']
        except AddressNotFoundError:
            time_zone = None
        if time_zone:
            timezone_object = pytz.timezone(time_zone)
            timezone.activate(timezone_object)
        else:
            timezone.deactivate()
        return self.get_response(request) 
开发者ID:meneses-pt,项目名称:goals.zone,代码行数:20,代码来源:timezone.py

示例3: get_location

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_location(ip_address: str) -> Optional[City]:
    """
    Searches for the country and city of a given IP address using Django's
    GeoIP2 library.

    :param ip_address: An IP address in string format
    :return: A City instance representing the location of the IP address, or
             None if not found.
    """
    geoip2 = GeoIP2()
    city = None
    try:
        geodata = geoip2.city(ip_address)
        if geodata.get('country_code') is not None:
            country, created = Country.objects.get_or_create(code=geodata['country_code'], defaults={
                'name': geodata['country_name']
            })
            if geodata.get('city') is not None:
                city, created = City.objects.get_or_create(name=geodata['city'], country=country)
    except AddressNotFoundError:
        logger.warning('Address not found for ip_address = "%s"' % ip_address)
    return city 
开发者ID:vitorfs,项目名称:colossus,代码行数:24,代码来源:utils.py

示例4: get_client_country_code

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_client_country_code(request):
    try:
        DEBUG_COUNTRY = request.GET.get('DEBUG_COUNTRY', None)
        if DEBUG_COUNTRY is not None:
            return DEBUG_COUNTRY
    except AttributeError:
        pass

    geoip2 = GeoIP2()

    try:
        return geoip2.country_code(get_client_ip(request))
    except:
        return "UNKNOWN"


#################################
# TODO: move to affiliation app #
################################# 
开发者ID:astrobin,项目名称:astrobin,代码行数:21,代码来源:utils.py

示例5: ip_to_location_info

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def ip_to_location_info(ip):
    """
    Get a dictionary of location info for a given IP address.

    The format of the dictionary is the same provided by the functions
    in django.contrib.gis.geoip2.base.GeoIP2.
    """

    if not HAS_GEOIP2:
        return None

    from django.contrib.gis.geoip2 import GeoIP2

    try:
        g = GeoIP2()
    except Exception as e:
        warnings.warn(str(e))
        return None

    try:
        return g.city(ip)
    except Exception:
        try:
            return g.country(ip)
        except Exception as e:
            warnings.warn(str(e)) 
开发者ID:QueraTeam,项目名称:django-qsessions,代码行数:28,代码来源:geoip.py

示例6: get_geoip_module

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_geoip_module():
    try:
        from django.contrib.gis.geoip2 import GeoIP2
        return GeoIP2
    except ImportError:
        logger.exception(
            'GeoIP module is disabled. To use GeoIP for the origin\n'
            'country personaliastion rule please set it up as per '
            'documentation:\n'
            'https://docs.djangoproject.com/en/stable/ref/contrib/gis/'
            'geoip2/.\n'
            'Wagtail-personalisation also works with Cloudflare and\n'
            'CloudFront country detection, so you should not see this\n'
            'warning if you use one of those.') 
开发者ID:wagtail,项目名称:wagtail-personalisation,代码行数:16,代码来源:rules.py

示例7: get_geoip_country

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_geoip_country(self, request):
        GeoIP2 = get_geoip_module()
        if GeoIP2 is None:
            return False
        return GeoIP2().country_code(get_client_ip(request)).lower() 
开发者ID:wagtail,项目名称:wagtail-personalisation,代码行数:7,代码来源:rules.py

示例8: test_get_geoip_module_disabled

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def test_get_geoip_module_disabled():
    with pytest.raises(ImportError):
        from django.contrib.gis.geoip2 import GeoIP2  # noqa
    assert get_geoip_module() is None 
开发者ID:wagtail,项目名称:wagtail-personalisation,代码行数:6,代码来源:test_rules_country_origin.py

示例9: test_get_geoip_module_enabled

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def test_get_geoip_module_enabled():
    from django.contrib.gis.geoip2 import GeoIP2
    assert get_geoip_module() is GeoIP2 
开发者ID:wagtail,项目名称:wagtail-personalisation,代码行数:5,代码来源:test_rules_country_origin.py

示例10: _load_geo_db

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def _load_geo_db():
    geo_db_path = getattr(settings, 'GEO_DB_PATH', None)
    if geo_db_path is None:
        if hasattr(settings, 'GEOIP_PATH'):
            g = GeoIP2()
            return g
        logging.error('[django-traffic] GEOIP_PATH or GEO_DB_PATH should be present in settings.py')
        return None
    return GeoIP2(path=geo_db_path) 
开发者ID:koslibpro,项目名称:django-traffic,代码行数:11,代码来源:middleware.py

示例11: get_queryset

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_queryset(self):
        queryset = Service.objects.all()
        # Order all the services by distance to the requester user location
        if 'lat' in self.request.query_params and 'lon' in self.request.query_params:
            # Brings lat and lon in request parameters
            ref_location = Point(float(self.request.query_params['lon']), float(
                self.request.query_params['lat']), srid=4326)
            if not self.request.user.is_anonymous and \
                    not self.request.user.location_manually_set:
                # If user is logged in, save his location
                self.request.user.location = ref_location
                self.request.user.save()
        elif not self.request.user.is_anonymous and (self.request.user.location is not None):
            # User has a location previously saved
            ref_location = self.request.user.location
        else:
            # if no location at all
            geoip = GeoIP2()
            ip = self.request.META['REMOTE_ADDR']
            try:
                ref_location = Point(geoip.lon_lat(ip), srid=4326)
            except AddressNotFoundError:
                logger.warning('Location could not been retrieved by any mean')
                ref_location = Point((-3.8196228, 40.4378698), srid=4326)  # Madrid
            if not self.request.user.is_anonymous:
                self.request.user.location = ref_location
                self.request.user.save()
        return queryset.annotate(dist=Distance('author__location', ref_location)).order_by('dist') 
开发者ID:Semillas,项目名称:semillas_platform,代码行数:30,代码来源:views.py

示例12: lookup_geo_up

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def lookup_geo_up(self, ip):
        """looks up the geographic coordinates of an IP address """
        if isinstance(settings.GEOIP_PATH, str):
            try:
                g = GeoIP2()
                geo_ip_obj = g.city(ip)
            except:
                geo_ip_obj = None
        else:
            geo_ip_obj = None
        return geo_ip_obj 
开发者ID:ekansa,项目名称:open-context-py,代码行数:13,代码来源:request.py

示例13: get_client_city_data

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get_client_city_data(ip_address):
    g = GeoIP2()
    try:
        return g.city(ip_address)
    except:
        return None 
开发者ID:codingforentrepreneurs,项目名称:Geolocator-2,代码行数:8,代码来源:utils.py

示例14: get

# 需要导入模块: from django.contrib.gis import geoip2 [as 别名]
# 或者: from django.contrib.gis.geoip2 import GeoIP2 [as 别名]
def get(self, request):
        resp_dict = {
            'login_error': request.GET.get('login_error', 0),
            'page': 'single',
            'org_types': OrganizationType.objects.all()
                .prefetch_related("claimtype_set").order_by('name'),
            'test_alarm': False}

        claim_type_sets = {}
        for org_type in resp_dict['org_types']:
            claim_type_set = []
            for claim_type in org_type.claimtype_set.all():
                claim_type_set.append({'id': claim_type.id,
                                      'value': claim_type.name})
            claim_type_sets[org_type.type_id] = claim_type_set

        resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets))

        if settings.RECAPTCHA_ENABLED is False:
            settings.RECAPTCHA_PUBLIC = ''
        resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC

        if settings.TEST_SERVER:
            resp_dict['test_alarm'] = True

        ip = get_client_ip(request)
        # cached_zoom = cache.get('lat_lon_for::%s' % ip)

        # if cached_zoom is not None:
        #     resp_dict['zoom_to']=cached_zoom
        # else:
        g = GeoIP2()
        try:
            if g.country(ip)['country_code'] == settings.COUNTRY_CODE:
                resp_dict['zoom_to'] = list(g.lat_lon(ip))
            else:
                resp_dict['zoom_to'] = settings.DEFAULT_ZOOM
        except AddressNotFoundError:
            resp_dict['zoom_to'] = settings.DEFAULT_ZOOM

            # cache.set('lat_lon_for::%s' % ip, resp_dict['zoom_to'])

        return render(request, self.template_name, resp_dict) 
开发者ID:autogestion,项目名称:corruption_tracker,代码行数:45,代码来源:views.py


注:本文中的django.contrib.gis.geoip2.GeoIP2方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。