本文整理汇总了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))
示例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'
示例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)
示例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
示例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
示例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()
示例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
示例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)
示例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)
示例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')
示例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()
示例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
示例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
示例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')
示例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)