示例#1
0
def nearby_items():
    response.content_type = 'application/json'

    if (nearby_param_validate(request) == False):
        return {'status': 'error-query-paras'}

    try:
        if (request.query.type == 'box'):
            bounds = geotypes.Box(float(request.query.north),
                                  float(request.query.east),
                                  float(request.query.south),
                                  float(request.query.west))
        elif (request.query.type == 'center'):
            center = geotypes.Point(float(request.query.lat),
                                    float(request.query.lon))
    except:
        return {'status': 'invalid-query-paras'}

    max_results = int(request.query.maxresults or '100')
    max_distance = float(request.query.maxdistance or '80000')  # 80 km ~ 50 mi

    try:
        base_query = Item.all()
        if (request.query.type == 'box'):
            results = Item.bounding_box_fetch(base_query,
                                              bounds,
                                              max_results=max_results)
        elif (request.query.type == 'center'):
            results = Item.proximity_fetch(base_query,
                                           center,
                                           max_results=max_results,
                                           max_distance=max_distance)
        return results_dump(results)
    except:
        return {'status': 'error-database-query'}
  def test_adjacent(self):
    cell = geocell.compute(geotypes.Point(37, -122), 14)
    box = geocell.compute_box(cell)

    # adjacency tests using bounding boxes
    self.assertEquals(box.north,
        geocell.compute_box(geocell.adjacent(cell, (0, 1))).south)
    self.assertEquals(box.south,
        geocell.compute_box(geocell.adjacent(cell, (0, -1))).north)
    self.assertEquals(box.east,
        geocell.compute_box(geocell.adjacent(cell, (1, 0))).west)
    self.assertEquals(box.west,
        geocell.compute_box(geocell.adjacent(cell, (-1, 0))).east)

    self.assertEquals(8, len(geocell.all_adjacents(cell)))

    # also test collinearity
    self.assertTrue(
        geocell.collinear(cell, geocell.adjacent(cell, (0, 1)), True))
    self.assertFalse(
        geocell.collinear(cell, geocell.adjacent(cell, (0, 1)), False))
    self.assertTrue(
        geocell.collinear(cell, geocell.adjacent(cell, (1, 0)), False))
    self.assertFalse(
        geocell.collinear(cell, geocell.adjacent(cell, (1, 0)), True))
  def test_compute(self):
    # a valid geocell
    cell = geocell.compute(geotypes.Point(37, -122), 14)
    self.assertEqual(14, len(cell))
    self.assertTrue(geocell.is_valid(cell))
    self.assertTrue(geocell.contains_point(cell, geotypes.Point(37, -122)))

    # a lower resolution cell should be a prefix to a higher resolution
    # cell containing the same point
    lowres_cell = geocell.compute(geotypes.Point(37, -122), 8)
    self.assertTrue(cell.startswith(lowres_cell))
    self.assertTrue(geocell.contains_point(lowres_cell,
                                          geotypes.Point(37, -122)))

    # an invalid geocell
    cell = geocell.compute(geotypes.Point(0, 0), 0)
    self.assertEqual(0, len(cell))
    self.assertFalse(geocell.is_valid(cell))
  def test_interpolation(self):
    cell = geocell.compute(geotypes.Point(37, -122), 14)
    sw_adjacent = geocell.adjacent(cell, (-1, -1))
    sw_adjacent2 = geocell.adjacent(sw_adjacent, (-1, -1))

    # interpolate between a cell and south-west adjacent, should return
    # 4 total cells
    self.assertEquals(4, len(geocell.interpolate(cell, sw_adjacent)))
    self.assertEquals(4, geocell.interpolation_count(cell, sw_adjacent))

    # interpolate between a cell and the cell SW-adjacent twice over,
    # should return 9 total cells
    self.assertEquals(9, len(geocell.interpolate(cell, sw_adjacent2)))
    self.assertEquals(9, geocell.interpolation_count(cell, sw_adjacent2))
示例#5
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'

        latitude = self.request.get('latitude')
        longitude = self.request.get('longitude')

        try:
            center = geotypes.Point(float(latitude), float(longitude))
        except ValueError:
            self.response.out.write(
                'latitude and longitude parameters must be valid latitude and longitude values.'
            )

        try:
            base_query = Stickup.all()
            results = Stickup.proximity_fetch(base_query,
                                              center,
                                              max_results=100,
                                              max_distance=80000)  #80 km

            json_results = []
            for result in results:
                json_results.append({
                    'latitude':
                    str(result.location.lat),
                    'user':
                    result.account.key().name(),
                    'time':
                    result.created_on.strftime(
                        '%Y-%m-%d %H:%M:%S +0000'),  #2010-02-11 19:37:17 +0000
                    'longitude':
                    str(result.location.lon),
                    'message':
                    result.message,
                })
        except:
            self.response.out.write(str(sys.exc_info()[1]))

        self.response.out.write(
            simplejson.dumps({
                'status': 200,
                'stickups': json_results
            }))
示例#6
0
文件: api.py 项目: ChrisEdson/Inquire
def questions(request):
    """
    API Method - /questions
    Returns a list of questions that are within geographical proximity
    to the passed in latitude/longitude.

    @method GET
    @param latitude: latitude of the location
    @param longitude longitude of the location

    @optional max_results: max number of questions to return, default=25
    @optional max_distance: max distance to search in miles
    
    @returns list of question objects
    """
    # required parameters
    latitude = float(request.GET.get("latitude"))
    longitude = float(request.GET.get("longitude"))

    # defines the center of our proximity search
    # geotypes.Point provided by geomodel project
    center = geotypes.Point(latitude, longitude)

    # default
    max_results = int(request.GET.get("max_results", 25))  # 25 results default
    max_distance = int(request.GET.get("max_distance", 50))  # 50 mile default

    # convert miles to kilometers
    max_distance = 1000 * max_distance / 0.621371192

    # Get all unclosed questions within the proximity max_distance and
    # limit to max_results
    base_query = Question.all().filter("closed =", False)
    questions = Question.proximity_fetch(base_query,
                                         center,
                                         max_results=max_results,
                                         max_distance=max_distance)

    return _json_response(questions=[q.to_json() for q in questions])
示例#7
0
  def get(self):
    _lng = cgi.escape(self.request.get('lng'))
    _lat = cgi.escape(self.request.get('lat'))
    _distance = 5

    center = geotypes.Point(float('14.550102'),
        float('121.056186'))

    #14.553803,121.050244

    #results = Location.proximity_fetch(Location.all(), center, max_results=10, max_distance=100000000)
  
    results = Location.all()

    public_attrs = Location.public_attributes()

    results_obj = [r.to_dict() for r in results]

    self.response.out.write(simplejson.dumps({
      'status': 'success',
      'results': results_obj
    }))
示例#8
0
    def get(self):
        def _simple_error(message, code=400):
            self.error(code)
            self.response.out.write(
                simplejson.dumps({
                    'status': 'error',
                    'error': {
                        'message': message
                    },
                    'results': []
                }))
            return None

        self.response.headers['Content-Type'] = 'application/json'
        query_type = self.request.get('type')
        user = self.request.get('user')

        if not query_type in ['proximity', 'bounds', 'user', 'default']:
            return _simple_error(
                'type parameter must be '
                'one of "proximity", "bounds", "user".',
                code=400)

        if query_type == 'proximity':
            try:
                center = geotypes.Point(float(self.request.get('lat')),
                                        float(self.request.get('lon')))
            except ValueError:
                return _simple_error(
                    'lat and lon parameters must be valid latitude '
                    'and longitude values.')
        elif query_type == 'bounds':
            try:
                bounds = geotypes.Box(float(self.request.get('north')),
                                      float(self.request.get('east')),
                                      float(self.request.get('south')),
                                      float(self.request.get('west')))
            except ValueError:
                return _simple_error(
                    'north, south, east, and west parameters must be '
                    'valid latitude/longitude values.')

        max_results = 100
        if self.request.get('maxresults'):
            max_results = int(self.request.get('maxresults'))

        max_distance = 8000000  # 80 km ~ 50 mi
        if self.request.get('maxdistance'):
            max_distance = float(self.request.get('maxdistance'))

        results = []
        try:
            # Can't provide an ordering here in case inequality filters are used.
            base_query = Listing.all()

            #if property_type:
            #base_query.filter('property_type =', property_type)

            # Natural ordering chosen to be public school enrollment.
            #base_query.order('-')

            # Perform proximity or bounds fetch.
            if query_type == 'proximity':
                results = Listing.proximity_fetch(base_query,
                                                  center,
                                                  max_results=max_results,
                                                  max_distance=max_distance)

            elif query_type == 'bounds':
                results = Listing.bounding_box_fetch(base_query,
                                                     bounds,
                                                     max_results=max_results)

            elif query_type == 'user':
                limit = self.request.get("limit")
                offset = self.request.get("offset")
                if not limit:
                    limit = 1000
                else:
                    limit = int(limit)
                if not offset:
                    offset = 0
                else:
                    offset = int(offset)
                results = base_query.fetch(limit, offset)

            public_attrs = Listing.public_attributes()

            results_obj = [
                _merge_dicts(
                    {
                        'lat': result.location.lat,
                        'lng': result.location.lon,
                    },
                    dict([(attr, getattr(result, attr))
                          for attr in public_attrs])) for result in results
            ]

            self.response.out.write(
                simplejson.dumps({
                    'status': 'success',
                    'results': results_obj,
                }))
        except:
            return _simple_error(str(sys.exc_info()[1]), code=500)
  def test_compute_box(self):
    cell = geocell.compute(geotypes.Point(37, -122), 14)
    box = geocell.compute_box(cell)

    self.assertTrue(box.south <= 37 and 37 <= box.north and
                    box.west <= -122 and -122 <= box.east)
示例#10
0
    def get(self):
        def _simple_error(message, code=400):
            self.error(code)
            self.response.out.write(
                simplejson.dumps({
                    'status': 'error',
                    'error': {
                        'message': message
                    },
                    'results': []
                }))
            return None

        self.response.headers['Content-Type'] = 'application/json'

        try:
            center = geotypes.Point(float(self.request.get('lat')),
                                    float(self.request.get('lon')))
        except ValueError:
            return _simple_error(
                'lat and lon parameters must be valid latitude and longitude values.'
            )

        max_results = self.request.get('results')
        try:
            max_results = int(
                max_results) if max_results else __default_max_results__
        except ValueError:
            return _simple_error('results must be a valid integer value')

        radius = self.request.get('radius')
        try:
            radius = int(radius) if radius else __default_radius__
        except ValueError:
            return _simple_error('radius must be a valid integer in meters')
        base_query = Parking.all()
        logging.info('radius is %d' % radius)
        logging.info('max results is %d' % max_results)
        results = Parking.proximity_fetch(base_query,
                                          center,
                                          max_results=max_results,
                                          max_distance=radius)
        logging.info('queried %d parkings' % len(results))
        results_arr = [{
            'id': result.parking_id,
            'name': result.name,
            'street': result.street_name,
            'house': result.house_number,
            'location': {
                'latitude': result.latitude,
                'longitude': result.longitude
            },
            'state': result.current_state,
            'capacity': result.capacity
        } for result in results]

        self.response.out.write(
            simplejson.dumps({
                'status': 'success',
                'results': results_arr
            },
                             indent=4))
示例#11
0
    def doSearch(self, cursor_key, **kwargs):
        query_type = self.request["query_type"]

        if not query_type in ['proximity', 'bounds']:
            return _simple_error(
                'El parámetro de búsqueda debe ser "proximity" o "bounds".',
                code=400)

        if query_type == 'proximity':
            try:
                center = geotypes.Point(float(self.request['lat']),
                                        float(self.request['lon']))
            except ValueError:
                return _simple_error(
                    'lat and lon parameters must be valid latitude and longitude values.',
                    code=400)

        elif query_type == 'bounds':
            try:
                bounds = geotypes.Box(float(self.request['north']),
                                      float(self.request['east']),
                                      float(self.request['south']),
                                      float(self.request['west']))
            except ValueError:
                return _simple_error(
                    'north, south, east, and west parameters must be valid latitude/longitude values.',
                    code=400)

        max_distance = 80000  # 80 km ~ 50 mi
        if self.request.has_key('max_distance'):
            max_distance = float(self.request['max_distance'])

        #---extirpado--
        base_query, price_data = create_query_from_dict(
            self.request, PropertyIndex)
        #---extirpado--

        max_results = MAX_QUERY_RESULTS
        if self.request.has_key('max_results'):
            max_results = int(self.request['max_results'])

        results, the_box, new_cursor_key = Property.bounding_box_fetch(
            base_query,
            bounds,
            max_results=max_results,
            cost_function=None,
            cursor_key=cursor_key)

        total_count = 'cientos'
        viewing_count = len(results)

        return {
            'properties':
            results,
            'total_count':
            total_count,
            'viewing':
            viewing_count,
            'the_box':
            '<br/>' + the_box + '<br/><br/>cursor_key:' + str(cursor_key),
            'cursor_key':
            new_cursor_key,
            'price_data':
            price_data
        }
示例#12
0
    def read(self, request):
        def paginated_response(collection):
            page = request.GET.get('page', 1)

            p = Paginator(collection, 10)

            try:
                results = p.page(page)
            except (EmptyPage, InvalidPage):
                results = p.page(p.num_pages)

            return {
                'resources': results.object_list,
                'num_pages': p.num_pages,
            }

        templates = None

        cache_key = make_cache_key(request)
        cache_data = memcache.get(cache_key)
        if cache_data:
            return cache_data

        if 'latitude' in request.GET and 'longitude' in request.GET:
            lat = float(request.GET['latitude'])
            lon = float(request.GET['longitude'])

            current_date = datetime.datetime.now().date()

            q = Venue.all()
            q.filter('start_date <= ', current_date)

            venues = Venue.proximity_fetch(q,
                                           geotypes.Point(lat, lon),
                                           max_results=20,
                                           max_distance=1609)

            results = []
            for venue in [
                    v if v.end_date >= current_date else None for v in venues
            ]:
                if venue:
                    q = Template.all().filter('venue =', venue.key())
                    templates = q.run(batch_size=1000)

                    results = results + [t.to_dict() for t in templates]

            venue_response = paginated_response(results)
            memcache.add(cache_key, venue_response, 120)
            return venue_response

        elif 'category' in request.GET:
            category = request.GET['category']

            q = Template.all().filter('category =', category.lower())
            q.filter('venue =', None)
            templates = q.run(batch_size=1000)

            category_response = paginated_response(
                [t.to_dict() for t in templates])
            memcache.add(cache_key, category_response, 120)
            return category_response
        else:
            templates = Template.all().filter('venue =', None).order('name')

            all_response = paginated_response([t.to_dict() for t in templates])
            memcache.add(cache_key, all_response, 120)
            return all_response
示例#13
0
  def get(self):
    def _simple_error(message, code=400):
      self.error(code)
      self.response.out.write(simplejson.dumps({
        'status': 'error',
        'error': { 'message': message },
        'results': []
      }))
      return None
      
    
    self.response.headers['Content-Type'] = 'application/json'
    query_type = self.request.get('type')
    
    if not query_type in ['proximity', 'bounds']:
      return _simple_error('type parameter must be '
                           'one of "proximity", "bounds".',
                           code=400)
    
    if query_type == 'proximity':
      try:
        center = geotypes.Point(float(self.request.get('lat')),
                                float(self.request.get('lon')))
      except ValueError:
        return _simple_error('lat and lon parameters must be valid latitude '
                             'and longitude values.')
    elif query_type == 'bounds':
      try:
        bounds = geotypes.Box(float(self.request.get('north')),
                              float(self.request.get('east')),
                              float(self.request.get('south')),
                              float(self.request.get('west')))
      except ValueError:
        return _simple_error('north, south, east, and west parameters must be '
                             'valid latitude/longitude values.')
    
    max_results = 100
    if self.request.get('maxresults'):
      max_results = int(self.request.get('maxresults'))
    
    max_distance = 80000 # 80 km ~ 50 mi
    if self.request.get('maxdistance'):
      max_distance = float(self.request.get('maxdistance'))

    school_type = None
    if self.request.get('schooltype'):
      try:
        school_type = int(self.request.get('schooltype'))
      except ValueError:
        return _simple_error('If schooltype is provided, '
                             'it must be a valid number, as defined in '
                             'http://nces.ed.gov/ccd/psadd.asp#type')

    grade_range = None
    if self.request.get('mingrade') or self.request.get('maxgrade'):
      try:
        grade_range = (int(self.request.get('mingrade')),
                       int(self.request.get('maxgrade')))
        if grade_range[0] > grade_range[1]:
          return _simple_error('mingrade cannot exceed maxgrade.')
      except ValueError:
        return _simple_error('If mingrade or maxgrade is provided, '
                             'both must be valid integers.')
      
    try:
      # Can't provide an ordering here in case inequality filters are used.
      base_query = PublicSchool.all()

      # Add in advanced options (rich query).
      if grade_range:
        if grade_range[0] == grade_range[1]:
          # WARNING: don't forget to build this edge case index!
          base_query.filter('grades_taught =', grade_range[0])
        else:
          (base_query.filter('grades_taught >=', grade_range[0])
                     .filter('grades_taught <=', grade_range[1]))
        
        # App Engine requires inequality filtered properties to be
        # the first ordering. Also apply this ordering for grades_taught =
        # filters to simplify indexes.
        base_query.order('grades_taught')
      
      if school_type:
        base_query.filter('school_type =', school_type)
      
      # Natural ordering chosen to be public school enrollment.
      base_query.order('-enrollment')
      
      # Perform proximity or bounds fetch.
      if query_type == 'proximity':
        results = PublicSchool.proximity_fetch(
            base_query,
            center, max_results=max_results, max_distance=max_distance)
      elif query_type == 'bounds':
        results = PublicSchool.bounding_box_fetch(
            base_query,
            bounds, max_results=max_results)
      
      public_attrs = PublicSchool.public_attributes()
      
      results_obj = [
          _merge_dicts({
            'lat': result.location.lat,
            'lng': result.location.lon,
            'lowest_grade_taught':
              min(result.grades_taught) if result.grades_taught else None,
            'highest_grade_taught':
              max(result.grades_taught) if result.grades_taught else None,
            },
            dict([(attr, getattr(result, attr))
                  for attr in public_attrs]))
          for result in results]

      self.response.out.write(simplejson.dumps({
        'status': 'success',
        'results': results_obj
      }))
    except:
      return _simple_error(str(sys.exc_info()[1]), code=500)