예제 #1
0
 def post(self, request):
     data = request.data
     if not data:
         data = request.POST
     queries = [data[p] for p in data if p.startswith('q_')]
     results = GEO_DAL.geolocate(queries)
     serializer = LocationSerializer(results,
                                     context={'request': request},
                                     many=True)
     return Response(serializer.data)
예제 #2
0
 def get(self, request):
     query = request.query_params.get('query', None)
     if not query:
         raise ValidationError('query was not provided.')
     results = GEO_DAL.geolocate([
         query,
     ])
     if results:
         results = results[0]
     serializer = LocationSerializer(results, context={'request': request})
     return Response(serializer.data)
예제 #3
0
 def post(self, request):
     map_type = request.query_params.get('type', None)
     country = request.query_params.get('country', None)
     state = request.query_params.get('state', None)
     county = request.query_params.get('county', None)
     city = request.query_params.get('city', None)
     zipcode = request.query_params.get('zipcode', None)
     region = request.query_params.get('region', None)
     name = request.query_params.get('name', None)
     error_message = self.__validate_query_params(country, state, county,
                                                  city, zipcode, map_type)
     if error_message:
         return Response({'error': error_message},
                         status=status.HTTP_400_BAD_REQUEST)
     map_type = GEO_DAL.get_map_type(map_type)
     domain = request.build_absolute_uri('/')[0:-1]
     if region:
         location = GEO_DAL.get_region(country, name)
         location_map = LocationMapGenerator(domain).get_regional_map(
             map_type, location)
     else:
         location = GEO_DAL.get_location(country, state, county, city,
                                         zipcode, name)
         location_map = LocationMapGenerator(
             domain).get_or_generate_location_map(map_type, location)
     if not location:
         return Response({'error': 'Location was not found.'},
                         status=status.HTTP_404_NOT_FOUND)
     serializer = LocationMapSerializer(location_map,
                                        context={'request': request})
     data = serializer.data
     url = data['map_file_url']
     if 'static' not in url:
         data['map_file_url'] = request.build_absolute_uri(
             settings.MEDIA_URL + data['map_file_url'])
     return Response(data)
예제 #4
0
 def get(self, request, id=None, *args, **kwargs):
     event = None
     isAdd = True
     if id:
         user = request.user
         event = EVENT_DAL.get_event_by_id(id)
         isAdd = False
         if not user.is_superuser:
             if event.submitted_by != user:
                 raise Http404()
     if not id and not event:
         settings = GEO_DAL.get_users_geography_settings(request.user)
         event = EventReport()
         event.location = settings.location
     form = self.form_class(instance=event)
     data = self.__get_data(form, request.user, isAdd)
     return render(request, self.template_name, data)
 def handle(self, *args, **options):
     domain = ''
     if settings.DEBUG:
         domain = 'http://localhost:8000'
     map_type = GEO_DAL.get_map_type('simple')
     for c in Cultivar.objects.all():
         location = c.origin_location
         if location:
             if not LocationMap.objects.filter(location=location).exists():
                 print('Creating Map for {0}-{1}'.format(c, location))
                 try:
                     if location.region:
                         LocationMapGenerator(domain).get_regional_map(
                             map_type, location)
                     else:
                         LocationMapGenerator(
                             domain).get_or_generate_location_map(
                                 map_type, location)
                     print('Success')
                 except Exception as e:
                     if 'look like a module path' in str(e):
                         raise e
                     print('Failed: {0}'.format(e))
예제 #6
0
    def post(self, request, *args, **kwargs):
        data = request.POST.copy()
        center = settings.DEFAULT_MAP_CENTER
        if 'new_location_lat_lon' in request.POST and request.POST[
                'new_location_lat_lon']:
            center = request.POST['new_location_lat_lon'].split(' ', 2)
            lat = get_standardized_coordinate(center[0])
            lon = get_standardized_coordinate(center[1])
            data['new_location_lat_lon'] = '{0} {1}'.format(lat, lon)

        zipcode = data['zipcode']
        zipcodeFailed = False
        hasMoved = 'location-moved' in data and data[
            'location-moved'] == 'moved'
        isNewLocation = data['location'] == 'new-location'

        if hasMoved:
            if zipcode:
                try:
                    data['zipcode'] = GEO_DAL.get_zipcode_by_zip(
                        zipcode).zipcode_id
                except:
                    zipcodeFailed = True
        if not isNewLocation:
            locationID = data['existing_location']
            location = GEO_DAL.get_location_by_id(locationID)
            zipcode = location.zipcode
            if not zipcode:
                zipcode = GEO_DAL.geocode_zipcode_from_lat_lon(
                    location.lat(), location.lon())
            data['zipcode'] = zipcode.zipcode_id

        form = self.form_class(data)
        isValid = True
        if not hasMoved and isNewLocation:
            form.add_error('__all__', 'Select a New Location.')
            isValid = False
        if zipcodeFailed:
            form.add_error('__all__', 'Zipcode could not be found.')
            isValid = False
        if form.is_valid() and isValid:
            """ TODO: REMOVE THE COMMENTS
            captcha = request.POST['g-recaptcha-response']
            captchaValidates = self.__does_captcha_validate(captcha)
            """
            captchaValidates = True
            if captchaValidates:
                signupModel = form.save(commit=False)
                valid = True
                locationError = self.__validate_location_return_error_or_location(
                    isNewLocation, signupModel)
                if locationError:
                    form.add_error('__all__', locationError)
                    valid = False
                if valid:
                    location = None
                    if isNewLocation:
                        zipcode = signupModel.zipcode
                        latLon = signupModel.new_location_lat_lon
                        locationName = signupModel.new_location_name
                        lat, lon = latLon.split(' ')
                        coord, created = GeoCoordinate.objects.get_or_create(
                            lat=lat, lon=lon)
                        location = GEO_DAL.create_location(
                            zipcode, coord, locationName)
                    else:
                        location = signupModel.existing_location

                    try:
                        user = User(
                            username=signupModel.username,
                            first_name=signupModel.first_name,
                            last_name=signupModel.last_name,
                            email=signupModel.email,
                        )
                        user.set_password(signupModel.password)
                        user.save()
                        setup_user_permissions_and_groups(user)
                        user.save()
                    except Exception as e:
                        form.add_error('__all__', e)
                        valid = False
                        try:
                            user.delete()
                        except:
                            pass

                    if valid:

                        userProfile = UserProfile(
                            organization=signupModel.organization,
                            location=location,
                            user=user)
                        userProfile.save()

                        if isNewLocation:
                            userLocation = UserLocation(
                                user=user,
                                location=location,
                                last_used=timezone.now(),
                                user_created=True)
                        else:
                            userLocation = UserLocation(
                                user=user,
                                location=location,
                                last_used=timezone.now(),
                                user_created=False)
                        userLocation.save()

                        loginUrl = reverse('admin:login')
                        return HttpResponseRedirect(loginUrl)
            else:
                form.add_error('__all__', 'Captcha did not validate.')
        data = {
            'form': form,
            'map_center': center,
            'has_moved': hasMoved,
            'zipcode': zipcode,
        }
        return render(request, self.template_name, data)
예제 #7
0
 def get_queryset(self):
     return GEO_DAL.get_all_named_locations()
예제 #8
0
    def __parse_location(self, cultivar, location):
        if not location:
            return
        if 'Region' in location:
            raise Exception('Regions cannot be handled yet.')
        us = Country.objects.get(name='United States of America')
        if ',' in location:

            match = FULL_RE.search(location)
            city = None
            county = None
            state = None
            zipcode = None
            lon = None
            lat = None
            location_name = None
            if match:
                city = match.group('city')
                state = match.group('state')
                zipcode = int(match.group('zip'))
                lat = float(match.group('lat'))
                lon = float(match.group('lon'))
                location_name = match.group('location_name')
            else:
                match = ZIP_COUNTY_RE.search(location)
                if match:
                    county = match.group('county')
                    state = match.group('state')
                    zipcode = int(match.group('zip'))
                else:
                    match = ZIP_CITY_RE.search(location)
                    if match:
                        city = match.group('city')
                        state = match.group('state')
                        zipcode = int(match.group('zip'))
                    else:
                        match = COUNTY_RE.search(location)
                        if match:
                            county = match.group('county')
                            state = match.group('state')
                        else:
                            match = CITY_RE.search(location)
                            if match:
                                city = match.group('city')
                                state = match.group('state')
                            else:
                                raise Exception(
                                    'Location {0} could not be parsed.'.format(
                                        location))
            state = State.objects.get(name__iexact=state.strip())
            location_obj = None
            query = Location.objects.filter(country=us)
            if zipcode:
                zipcode = Zipcode.objects.get(zipcode=zipcode)
            if location_name:
                query = query.filter(name=location_name.strip()).first()
                if not query:
                    location_obj = Location()
                    location_obj.country = us
                    location_obj.state = state
                    location_obj.city = City.objects.get(state=state,
                                                         name__iexact=city)
                    location_obj.zipcode = zipcode
                    location_obj.name = location_name
                    location_obj.geocoordinate = GEO_DAL.get_or_create_geocoordinate(
                        lat, lon)
                    print('Creating {0}'.format(location_obj))
                    location_obj.save()
            else:
                query = query.filter(state=state, zipcode=zipcode)
                if city:
                    query = query.filter(city__name__iexact=city.strip())
                if county:
                    query = query.filter(county__name__iexact=county.strip(),
                                         city__isnull=True)
                """
                query = query.filter(state=state)
                """
                location_obj = query.first()
                if not location_obj:
                    print('Location:' + str(location))
                    raise Exception(
                        'A location object was expected, but none was found for {0}'
                        .format(location))
            if location_obj:
                print('Setting {0} location to {1}'.format(
                    cultivar, location_obj))
                cultivar.origin_location = location_obj
        else:
            location = location.strip()
            state = State.objects.filter(name=location).first()
            if not state:  # Location is Country
                country = Location.objects.filter(country__name=location,
                                                  region=None,
                                                  state=None,
                                                  name=None).first()
                if not country:
                    raise Exception(
                        'Country {0} does not exist.'.format(location))
                else:
                    print('Setting {0} location to {1}'.format(
                        cultivar, country))
                    cultivar.origin_location = country
            else:
                location = Location.objects.get(country=us,
                                                state=state,
                                                county=None,
                                                city=None,
                                                zipcode=None)
                print('Setting {0} location to {1}'.format(cultivar, location))
                cultivar.origin_location = location