示例#1
0
    def save(self, *args, **kwargs):
        url = ''
        if self.country in (None, u""):
            if slugify(self.address.lower()) in [x[0] for x in CONTINENTS]:
                continent = self.address
            else:
                continent = u'undefined'
        else:
            continent = country_to_continent(self.country)
            if continent is None:
                raise NotImplementedError(
                    (u"The Country you are looking for for the current "
                     u"address '{}' is not in our list".format(self.address)))

        url += '/{}'.format(slugify(continent))
        gmap_ent, create = GmapsItem.objects.get_or_create(
            geo_type='continent', name=continent,
            slug=slugify(continent), url=url)
        self.continent_item = gmap_ent
        # set all the other types
        for tp in URL_TYPES:
            curr_type = getattr(self, tp)
            url_to_add = slugify(curr_type) if curr_type not in (None, '')\
                else u"-"
            url += '/{}'.format(url_to_add)
            if curr_type:
                geocode = self.geocode if self.geo_type == tp else None
                gmap_ent, create = GmapsItem.objects.get_or_create(
                    geo_type=tp, name=curr_type,
                    slug=slugify(curr_type), url=url)
                gmap_ent.geocode = geocode
                gmap_ent.save()
                setattr(self, u"{}_item".format(tp), gmap_ent)
        super(GmapsPlace, self).save(*args, **kwargs)
    def save(self, *args, **kwargs):
        url = ''
        if self.country in (None, u""):
            if slugify(self.address.lower()) in [x[0] for x in CONTINENTS]:
                continent = self.address
            else:
                continent = u'undefined'
        else:
            continent = country_to_continent(self.country)
            if continent is None:
                raise NotImplementedError(
                    u"The Country you are looking for for the current address '{}' is not in our list"
                    .format(self.address))

        url += '/{}'.format(slugify(continent))
        gmap_ent, create = GmapsItem.objects.get_or_create(
            geo_type='continent',
            name=continent,
            slug=slugify(continent),
            url=url)
        self.continent_item = gmap_ent
        # set all the other types
        for tp in ALLOWED_TYPES:
            curr_type = getattr(self, tp)
            url_to_add = slugify(curr_type) if curr_type not in (None, '')\
                else u"-"
            url += '/{}'.format(url_to_add)
            if curr_type:
                geocode = self.geocode if self.geo_type == tp else None
                gmap_ent, create = GmapsItem.objects.get_or_create(
                    geo_type=tp,
                    name=curr_type,
                    slug=slugify(curr_type),
                    url=url)
                gmap_ent.geocode = geocode
                gmap_ent.save()
                setattr(self, u"{}_item".format(tp), gmap_ent)
        super(GmapsPlace, self).save(*args, **kwargs)
    def get_or_create_from_geocode(cls, lat, lng, geo_type, url='', bkp_name=''):
        try:
            response = gmaps_api_reverse(
                float(lat), float(lng), result_type=[geo_type, ],
                **GMAPS_DEFAULT_REVERSE_PARAMS)
        except NoResults:
            response = gmaps_api_reverse(
                float(lat), float(lng),
                **GMAPS_DEFAULT_REVERSE_PARAMS)
        new_gmi = None
        found = False
        for res in response:
            if geo_type in res['types']:
                found = True
                try:
                    new_gmi = GmapsItem.objects.get(place_id=res['place_id'], geo_type=geo_type)
                except GmapsItem.DoesNotExist:
                    place_id = res['place_id']
                    lat = res['geometry']['location']['lat']
                    lng = res['geometry']['location']['lng']
                    geocode = "{},{}".format(lat, lng)
                    name = None
                    short_name = None
                    slug = None
                    for addr in res['address_components']:
                        if geo_type in addr['types']:
                            name = addr['long_name']
                            short_name = addr['short_name']
                            slug = slugify(name)
                            break
                    url_to_append = "{}/{}".format(url, slug)
                    new_gmi = GmapsItem.objects.create(
                        geo_type=geo_type,
                        slug=slug,
                        geocode=geocode,
                        place_id=place_id,
                        name=name,
                        short_name=short_name,
                        response_json=json.dumps(res),
                        url=url_to_append
                    )
                else:
                    break

        if not found and geo_type == 'continent':
            country_temp = None
            for addr in response[0]['address_components']:
                if 'country' in addr['types']:
                    country_temp = addr['long_name']
                    break
            if country_temp in (None, ''):
                raise ValueError('Continent not found')
                # undefined
            else:
                continent = country_to_continent(country_temp)
                if continent is None:
                    raise NotImplementedError(
                        (u"The Country you are looking for, related to the current "
                         u"latlng '{},{}', is not in our list".format(lat, lng)))
            # set the "home-made" continent
            url += '/{}'.format(slugify(continent))
            new_gmi, create = GmapsItem.objects.get_or_create(
                geo_type='continent', name=continent,
                slug=slugify(continent), url=url,
                defaults={'place_id': str(uuid.uuid4()),
                          'geocode': "{},{}".format(lat, lng)})
        elif not found:
            response = gmaps_api_geocode(
                address=cls._build_address_from_url(url + slugify(bkp_name)),
                **GMAPS_DEFAULT_GEOCODE_PARAMS)
            for res in response:
                if geo_type in res['types']:
                    found = True
                    try:
                        new_gmi = GmapsItem.objects.get(place_id=res['place_id'],
                                                        geo_type=geo_type)
                    except GmapsItem.DoesNotExist:
                        place_id = res['place_id']
                        lat = res['geometry']['location']['lat']
                        lng = res['geometry']['location']['lng']
                        geocode = "{},{}".format(lat, lng)
                        name = None
                        short_name = None
                        slug = None
                        for addr in res['address_components']:
                            if geo_type in addr['types']:
                                name = addr['long_name']
                                short_name = addr['short_name']
                                slug = slugify(name)
                                break
                        url_to_append = "{}/{}".format(url, slug)
                        new_gmi = GmapsItem.objects.create(
                            geo_type=geo_type,
                            slug=slug,
                            geocode=geocode,
                            place_id=place_id,
                            name=name,
                            short_name=short_name,
                            response_json=json.dumps(res),
                            url=url_to_append
                        )
                    else:
                        break

        return new_gmi
    def get_or_create_from_geocode(cls,
                                   lat,
                                   lng,
                                   geo_type,
                                   url='',
                                   bkp_name=''):
        try:
            response = gmaps_api_reverse(float(lat),
                                         float(lng),
                                         result_type=[
                                             geo_type,
                                         ],
                                         **GMAPS_DEFAULT_REVERSE_PARAMS)
        except NoResults:
            response = gmaps_api_reverse(float(lat), float(lng),
                                         **GMAPS_DEFAULT_REVERSE_PARAMS)
        new_gmi = None
        found = False
        for res in response:
            if geo_type in res['types']:
                found = True
                try:
                    new_gmi = GmapsItem.objects.get(place_id=res['place_id'],
                                                    geo_type=geo_type)
                except GmapsItem.DoesNotExist:
                    place_id = res['place_id']
                    lat = res['geometry']['location']['lat']
                    lng = res['geometry']['location']['lng']
                    geocode = "{},{}".format(lat, lng)
                    name = None
                    short_name = None
                    slug = None
                    for addr in res['address_components']:
                        if geo_type in addr['types']:
                            name = addr['long_name']
                            short_name = addr['short_name']
                            slug = slugify(name)
                            break
                    url_to_append = "{}/{}".format(url, slug)
                    new_gmi = GmapsItem.objects.create(
                        geo_type=geo_type,
                        slug=slug,
                        geocode=geocode,
                        place_id=place_id,
                        name=name,
                        short_name=short_name,
                        response_json=json.dumps(res),
                        url=url_to_append)
                else:
                    break

        if not found and geo_type == 'continent':
            country_temp = None
            for addr in response[0]['address_components']:
                if 'country' in addr['types']:
                    country_temp = addr['long_name']
                    break
            if country_temp in (None, ''):
                raise ValueError('Continent not found')
                # undefined
            else:
                continent = country_to_continent(country_temp)
                if continent is None:
                    raise NotImplementedError((
                        u"The Country you are looking for, related to the current "
                        u"latlng '{},{}', is not in our list".format(lat,
                                                                     lng)))
            # set the "home-made" continent
            url += '/{}'.format(slugify(continent))
            new_gmi, create = GmapsItem.objects.get_or_create(
                geo_type='continent',
                name=continent,
                slug=slugify(continent),
                url=url,
                defaults={
                    'place_id': str(uuid.uuid4()),
                    'geocode': "{},{}".format(lat, lng)
                })
        elif not found:
            response = gmaps_api_geocode(
                address=cls._build_address_from_url(url + slugify(bkp_name)),
                **GMAPS_DEFAULT_GEOCODE_PARAMS)
            for res in response:
                if geo_type in res['types']:
                    found = True
                    try:
                        new_gmi = GmapsItem.objects.get(
                            place_id=res['place_id'], geo_type=geo_type)
                    except GmapsItem.DoesNotExist:
                        place_id = res['place_id']
                        lat = res['geometry']['location']['lat']
                        lng = res['geometry']['location']['lng']
                        geocode = "{},{}".format(lat, lng)
                        name = None
                        short_name = None
                        slug = None
                        for addr in res['address_components']:
                            if geo_type in addr['types']:
                                name = addr['long_name']
                                short_name = addr['short_name']
                                slug = slugify(name)
                                break
                        url_to_append = "{}/{}".format(url, slug)
                        new_gmi = GmapsItem.objects.create(
                            geo_type=geo_type,
                            slug=slug,
                            geocode=geocode,
                            place_id=place_id,
                            name=name,
                            short_name=short_name,
                            response_json=json.dumps(res),
                            url=url_to_append)
                    else:
                        break

        return new_gmi