示例#1
0
	def checksum(self):
		"""
		Calculate a checksum of this Blip.
		Note: Currently this is only the SHA-1 of the Blip's text. This is
		tentative and subject to change
		
		"""
		return sha1(self.text.encode("utf-8")).hexdigest()
示例#2
0
 def inner(request, *args, **kwargs):
     need_to_set_the_cookie = False
     csrf_token = request.COOKIES.get('_csrf_cookie')
     if not csrf_token:
         need_to_set_the_cookie = True
         csrf_token = sha1(str(random.random())).hexdigest()
         request._csrf_token_to_set = csrf_token
     response = view_func(request, *args, **kwargs)
     if need_to_set_the_cookie:
         response.set_cookie('_csrf_cookie', csrf_token)
     return response
示例#3
0
class LayarView(object):
    '''
        Class-based generic view for creating a Layar endpoint.

        To add a layar it is necessary to write two functions:
            ``get_LAYERNAME_queryset``
                This function is passed latitude, longitude, radius,
                radio_option, search_query, and slider_value parameters.

                radio_option, search_query, and slider_value may be None
                depending on how you've configured your widgets on layar.com

                **Note:** It is strongly recommended that you make this function
                accept **kwargs for maximum compatibility

            ``poi_from_LAYERNAME_item(item)``
                convert an item of whatever type is returned by 
                :func:`get_LAYARNAME_queryset` into a ``POI`` object

        This separation allows LayarView to handle pagination correctly.

        Your derived class can also set a number of options.  The defaults
        should be suitable for most purposes as Layar doesn't display more
        than 50 points.

        ``results_per_page``
            controls the number of results returned at once (default: 15)
        ``max_results``
            controls the maximum number of results across all pages (default: 50)
        ``verify_hash``
            set to False to disable hash verification (useful for testing)
        ``default_radius``
            radius to use if a radius is not passed
    '''

    results_per_page = 15
    max_results = 50
    default_radius = 1000
    verify_hash = False

    def __call__(self, request):
        try:
            # parameters from http://layar.pbworks.com/GetPointsOfInterest

            # required parameters
            user_id = request.GET['userId']
            #developer_id = request.GET['developerId']
            developer_hash = request.GET['developerHash']
            timestamp = request.GET['timestamp']
            layer_name = request.GET['layerName']
            lat = float(request.GET['lat'])
            lon = float(request.GET['lon'])

            # optional
            accuracy = request.GET.get('accuracy')
            if accuracy:
                accuracy = int(accuracy)
            radius = request.GET.get('radius')
            if radius:
                radius = int(radius)
            alt = request.GET.get('alt')
            if alt:
                alt = int(alt)
            page = int(request.GET.get('pageKey', 0))

            # user defined UI elements
            radio_option = request.GET.get('RADIOLIST')
            search = request.GET.get('SEARCHBOX')
            search2 = request.GET.get('SEARCHBOX_2')
            search3 = request.GET.get('SEARCHBOX_3')
            slider = request.GET.get('CUSTOM_SLIDER')
            slider2 = request.GET.get('CUSTOM_SLIDER_2')
            slider3 = request.GET.get('CUSTOM_SLIDER_3')
            checkboxes = request.GET.get('CHECKBOXLIST')
            if checkboxes:
                checkboxes = checkboxes.split(',')

        except KeyError, e:
            return HttpResponseBadRequest('missing required parameter: %s' % e)

        layar_response = dict(hotspots=[], layer=layer_name, errorCode=0,
                          errorString='ok', nextPageKey=None, morePages=False)

        try:

            # verify hash
            if self.verify_hash:
                key = self.developer_key + timestamp
                if sha1(key).hexdigest() != developer_hash:
                    raise LayarException(20, 'Bad developerHash')

            # get ``max_results`` items from queryset
            try:
                qs_func = getattr(self, 'get_%s_queryset' % layer_name)
            except AttributeError:
                raise LayarException(21, 'no such layer: %s' % layer_name)

            qs = qs_func(latitude=lat, longitude=lon, radius=radius,
                         radio_option=radio_option, search_query=search,
                         search_query2=search2, search_query3=search3,
                         slider_value=slider, slider_value2=slider2,
                         slider_value3=slider3, checkboxes=checkboxes)
            qs = qs[:self.max_results]

            # do pagination if results_per_page is set
            if self.results_per_page:
                start_index = self.results_per_page * page
                end_index = start_index + self.results_per_page

                # if there are more pages, indicate that in response
                if end_index < qs.count()-1:
                    layar_response['morePages'] = True
                    layar_response['nextPageKey'] = str(page+1)

                qs = qs[start_index:end_index]

            # convert queryset into POIs
            try:
                poi_func = getattr(self, 'poi_from_%s_item' % layer_name)
            except AttributeError:
                raise LayarException(21, 'no such layer: %s' % layer_name)

            pois = [poi_func(item) for item in qs]
            layar_response['hotspots'] = [poi.to_dict() for poi in pois]

            # if radius wasn't sent pass back the radius used
            if not radius:
                layar_response['radius'] = self.default_radius

        except LayarException, e:
            layar_response['errorCode'] = e.code
            layar_response['errorString'] = e.message