當前位置: 首頁>>代碼示例>>Python>>正文


Python errors.AddressNotFoundError方法代碼示例

本文整理匯總了Python中geoip2.errors.AddressNotFoundError方法的典型用法代碼示例。如果您正苦於以下問題:Python errors.AddressNotFoundError方法的具體用法?Python errors.AddressNotFoundError怎麽用?Python errors.AddressNotFoundError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在geoip2.errors的用法示例。


在下文中一共展示了errors.AddressNotFoundError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: each

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def each(ip):
        try:
            if reader:
                response = reader.city(ip.value)
                ip.geoip = {
                    "country": response.country.iso_code,
                    "city": response.city.name
                }
                ip.save()
        except ObservableValidationError:
            logging.error(
                "An error occurred when trying to add {} to the database".
                format(ip.value))
        except AddressNotFoundError:
            logging.error(
                "{} was not found in the GeoIp database".format(ip.value)) 
開發者ID:yeti-platform,項目名稱:yeti,代碼行數:18,代碼來源:process_ip.py

示例2: get_iso_country_code

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def get_iso_country_code(ip):
    db_path = os.path.join(
        settings.BASE_DIR,
        'metrics',
        'geolocation',
        'GeoLite2-Country.mmdb',
    )
    reader = geoip2.database.Reader(db_path)

    try:
        response = reader.country(ip)
        return response.country.iso_code if response.country.iso_code else 'OTHER'
    except AddressNotFoundError:
        if ip == '127.0.0.1':
            return "GB"
        return 'OTHER' 
開發者ID:BirkbeckCTP,項目名稱:janeway,代碼行數:18,代碼來源:logic.py

示例3: __call__

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [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

示例4: get_location

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [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

示例5: process

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def process(self, indicator):
        if indicator.itype not in ['ipv4', 'ipv6', 'fqdn', 'url']:
            return indicator

        if indicator.is_private():
            return indicator

        # https://geoip2.readthedocs.org/en/latest/
        i = str(indicator.indicator)
        tmp = indicator.indicator

        if indicator.itype in ['ipv4', 'ipv6']:
            match = re.search('^(\S+)\/\d+$', i)
            if match:
                indicator.indicator = match.group(1)

        try:
            if indicator.indicator:
                self._resolve(indicator)
            indicator.indicator = tmp
        except AddressNotFoundError as e:
            self.logger.warn(e)
            indicator.indicator = tmp

        return indicator 
開發者ID:csirtgadgets,項目名稱:bearded-avenger,代碼行數:27,代碼來源:geo.py

示例6: city

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def city(self, address):  # pylint: disable=too-complex,inconsistent-return-statements,no-self-use,too-many-return-statements
        if address == '128.101.101.101':
            return MockResponse(location=MockLocation(latitude=44.9759, longitude=-93.2166))
        if address == '1.2.3.4':
            return MockResponse(location=MockLocation(latitude=47.913, longitude=-122.3042))
        if address == '1.1.1.123':
            return MockResponse(location=MockLocation(latitude=-37.7, longitude=145.1833))
        if address == '255.255.255.255':
            return MockResponse(location=MockLocation(latitude=0.0, longitude=0.0))
        if address == '192.0.2.16':
            return MockResponse(location=MockLocation(latitude=1.1, longitude=1.1))
        if address == '1234:1234:abcd:abcd:1234:1234:abcd:abcd':
            return MockResponse(location=MockLocation(latitude=2.1, longitude=2.1))
        if address == '2001:db8:0:0:8d3::':
            return MockResponse(location=MockLocation(latitude=3.1, longitude=3.1))
        if address == '127.101.101.101':
            return MockResponse(location=MockLocation(latitude=4.1, longitude=4.1))
        if address == '1.1.2.345':
            raise AddressNotFoundError()
        if address == 'aaa':
            raise ValueError() 
開發者ID:fkie-cad,項目名稱:FACT_core,代碼行數:23,代碼來源:test_ip_and_uri_finder.py

示例7: get_country_code

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def get_country_code(ip_address):
    if geoip_reader and ip_address:
        try:
            return geoip_reader.country(ip_address).country.iso_code
        except AddressNotFoundError:
            pass
        except GeoIP2Error as exc:
            logger.warning(exc, extra={"code": WARNING_UNKNOWN_GEOIP_ERROR})
            pass

    return None 
開發者ID:mozilla,項目名稱:normandy,代碼行數:13,代碼來源:geolocation.py

示例8: _get_countries

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def _get_countries(addresses: List[str], reader: Reader) -> List[str]:
    res = set()
    for ip in addresses:
        try:
            geoip_result = reader.country(ip)
            this_result = geoip_result.country.name
            if not this_result:
                this_result = geoip_result.continent.name
            if not this_result:
                raise AddressNotFoundError
            res.add(this_result)
        except AddressNotFoundError:
            # TODO: Add entry specifying that at least one location has not been found
            continue
    return list(res) 
開發者ID:PrivacyScore,項目名稱:PrivacyScore,代碼行數:17,代碼來源:network.py

示例9: create_product

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def create_product():
    form = ProductForm()

    if form.validate_on_submit():
        name = form.name.data
        price = form.price.data
        category = Category.query.get_or_404(
            form.category.data
        )
        image = request.files and request.files['image']
        filename = ''
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        reader = geoip2.database.Reader('GeoLite2-City_20190416/GeoLite2-City.mmdb')
        try:
            match = reader.city(request.remote_addr)
        except AddressNotFoundError:
            match = None
        product = Product(
            name, price, category, filename,
            match and match.location.time_zone or 'Localhost'
        )
        db.session.add(product)
        db.session.commit()
        flash(
            _('The product %(name)s has been created', name=name),
            'success'
        )
        return redirect(url_for('catalog.product', id=product.id))

    if form.errors:
        flash(form.errors, 'danger')

    return render_template('product-create.html', form=form) 
開發者ID:PacktPublishing,項目名稱:Flask-Framework-Cookbook-Second-Edition,代碼行數:37,代碼來源:views.py

示例10: get_queryset

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [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

示例11: run

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def run(self):
        Analyzer.run(self)

        if self.data_type == 'ip':
            try:
                data = self.get_data()

                city = geoip2.database.Reader(os.path.dirname(__file__) + '/GeoLite2-City.mmdb').city(data)

                self.report({
                    'city': self.dump_city(city.city),
                    'continent': self.dump_continent(city.continent),
                    'country': self.dump_country(city.country),
                    'location': self.dump_location(city.location),
                    'registered_country': self.dump_country(city.registered_country),
                    'represented_country': self.dump_country(city.represented_country),
                    'subdivisions': self.dump_country(city.subdivisions.most_specific),
                    'traits': self.dump_traits(city.traits)
                })
            except ValueError as e:
                self.error('Invalid IP address')
            except AddressNotFoundError as e:
                self.error('Unknown IP address')
            except Exception as e:
                self.unexpectedError(type(e))
        else:
            self.notSupported() 
開發者ID:TheHive-Project,項目名稱:Cortex-Analyzers,代碼行數:29,代碼來源:geo.py

示例12: geo_locate

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def geo_locate(ip):
    from personal_mycroft_backend.settings import DEFAULT_LOCATION
    if ip in ["0.0.0.0", "127.0.0.1"]:
        ip = str(check_output(['hostname', '--all-ip-addresses'])).split(" ")[0][2:]
    try:
        data = ip_database.city(ip)
        return location_dict(**data.raw)
    except AddressNotFoundError:
        return DEFAULT_LOCATION 
開發者ID:MycroftAI,項目名稱:personal-backend,代碼行數:11,代碼來源:__init__.py

示例13: link_ips_with_geo_location

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def link_ips_with_geo_location(self, ip_addresses):
        linked_ip_geo_list = []
        for ip in ip_addresses:
            try:
                ip_tuple = ip, self.find_geo_location(ip)
            except (AttributeError, AddressNotFoundError, FileNotFoundError, ValueError, InvalidDatabaseError) as exception:
                logging.debug('{} {}'.format(type(exception), str(exception)))
                ip_tuple = ip, ''
            linked_ip_geo_list.append(ip_tuple)
        return linked_ip_geo_list 
開發者ID:fkie-cad,項目名稱:FACT_core,代碼行數:12,代碼來源:ip_and_uri_finder.py

示例14: test_find_geo_location

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def test_find_geo_location(self):
        self.assertEqual(self.analysis_plugin.find_geo_location('128.101.101.101'), '44.9759, -93.2166')
        self.assertEqual(self.analysis_plugin.find_geo_location('127.101.101.101'), '4.1, 4.1')

        with self.assertRaises(AddressNotFoundError):
            self.analysis_plugin.find_geo_location('1.1.2.345')
        with self.assertRaises(ValueError):
            self.analysis_plugin.find_geo_location('aaa') 
開發者ID:fkie-cad,項目名稱:FACT_core,代碼行數:10,代碼來源:test_ip_and_uri_finder.py

示例15: create_product

# 需要導入模塊: from geoip2 import errors [as 別名]
# 或者: from geoip2.errors import AddressNotFoundError [as 別名]
def create_product():
    form = ProductForm()

    if form.validate_on_submit():
        name = form.name.data
        price = form.price.data
        category = Category.query.get_or_404(
            form.category.data
        )
        image = request.files and request.files['image']
        filename = ''
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            session = boto3.Session(
                aws_access_key_id=app.config['AWS_ACCESS_KEY'],
                aws_secret_access_key=app.config['AWS_SECRET_KEY']
            )
            s3 = session.resource('s3')
            bucket = s3.Bucket(app.config['AWS_BUCKET'])
            if bucket not in list(s3.buckets.all()):
                bucket = s3.create_bucket(
                    Bucket=app.config['AWS_BUCKET'],
                    CreateBucketConfiguration={
                        'LocationConstraint': 'ap-south-1'
                    },
                )
            bucket.upload_fileobj(
                image, filename,
                ExtraArgs={'ACL': 'public-read'})
        reader = geoip2.database.Reader('GeoLite2-City_20190416/GeoLite2-City.mmdb')
        try:
            match = reader.city(request.remote_addr)
        except AddressNotFoundError:
            match = None

        product = Product(
            name, price, category, filename,
            match and match.location.time_zone or 'Localhost'
        )
        db.session.add(product)
        db.session.commit()
        flash(
            _('The product %(name)s has been created', name=name),
            'success'
        )
        return redirect(url_for('catalog.product', id=product.id))

    if form.errors:
        flash(form.errors, 'danger')

    return render_template('product-create.html', form=form) 
開發者ID:PacktPublishing,項目名稱:Flask-Framework-Cookbook-Second-Edition,代碼行數:53,代碼來源:views.py


注:本文中的geoip2.errors.AddressNotFoundError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。