def _locate_user(self, access_points): """ Will use Brett's kNN algorithm with the list of access points to determine the location. Currently, returned a random location within Halligan""" modified_aps = { ap['mac_address']: ap['signal_strength'] for ap in access_points } found, x_coord, y_coord, floor_id = kNN(connection.cursor(), modified_aps) if not found: msg = 'Could not locate you' raise ImmediateHttpResponse(HttpNotFound(msg)) try: floor = Floor.objects.get(pk=floor_id) except Floor.DoesNotExist: msg = 'Could not locate you' raise ImmediateHttpResponse(HttpNotFound(msg)) # Convert information to a location object location_object = LocateMeObject() location_object.building_name = floor.building_name location_object.floor_number = floor.floor_number location_object.x_coordinate = int(x_coord) location_object.y_coordinate = int(y_coord) location_object.image_url = floor.image.url return location_object
def respond_to_request(self, request, **kwargs): """Allows a user to respond to a request for their location""" self._verify(request) data = self.deserialize(request, request.body, format=request.META.get( 'Content-Type', 'application/json')) allow_request = data.get('allow_request', None) requestor_id = data.get('requestor_id', None) access_points = data.get('access_points', None) if allow_request is None or requestor_id is None: msg = 'Need both allow_request and requestor_id' raise ImmediateHttpResponse(HttpBadRequest(msg)) if allow_request and access_points is None or len(access_points) < 1: msg = 'If allow_request, then access_points must be provided' raise ImmediateHttpResponse(HttpBadRequest(msg)) # Make sure the requestor actually exists try: requestor = User.objects.get(pk=requestor_id) requestor_device_set = requestor.userdevice_set.all() except User.DoesNotExist: msg = 'Could not find User with id {}'.format(requestor_id) raise ImmediateHttpResponse(HttpNotFound(msg)) # And also make sure the requestor has a phone if not requestor_device_set.exists(): msg = 'Could not find User with id {}'.format(requestor_id) raise ImmediateHttpResponse(HttpNotFound(msg)) if allow_request: location = self._locate_user(access_points) self._save_user_location(request.user, location) msg = { 'type': 'request_granted', 'friend': request.user.get_full_name(), 'building_name': location.building_name, 'floor_number': location.floor_number, 'x_coordinate': location.x_coordinate, 'y_coordinate': location.y_coordinate, 'friend_id': request.user.pk, 'image_url': location.image_url, } else: msg = { 'type': 'request_denied', 'friend': request.user.get_full_name(), 'friend_id': request.user.pk } response_class = self._notify_user(requestor_device_set, msg) return self.create_response(request, data={}, response_class=response_class)
def patch_detail(self, request, **kwargs): """ Updates a resource in-place. We could also override obj_update, which is the Tastypie intended-way of having a custom PATCH implementation, but this method gets a full updated object bundle that is expected to be directly written to the object. In this method, we still have access to what actually really comes as part of the update payload. If the resource is updated, return ``HttpAccepted`` (202 Accepted). If the resource did not exist, return ``HttpNotFound`` (404 Not Found). """ try: # Fetch relevant node object as Tastypie does it basic_bundle = self.build_bundle(request=request) obj = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpNotFound() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") # Deserialize incoming update payload JSON from request deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) if 'properties' in deserialized: obj.set_attrs(deserialized['properties']) # return the updated edge object return HttpResponse(obj.to_json(), 'application/json', status=202)
def _internal_get_bbox_AS(request, **kwargs): q = request.GET.get('q', '').strip() m = re.match( '(?P<lowlat>-?[\d\.]+),(?P<lowlon>-?[\d\.]+),(?P<highlat>-?[\d\.]+),(?P<highlon>-?[\d\.]+)', q) sclazz = request.GET.get('clazz', '').strip() clazz = [] if sclazz: clazz = sclazz.split(',') if not m: raise ImmediateHttpResponse(response=HttpNotFound()) lowlat = float(m.group('lowlat')) lowlon = float(m.group('lowlon')) highlon = float(m.group('highlon')) highlat = float(m.group('highlat')) zone_bbox = Polygon( ((float(lowlat), float(lowlon)), (float(lowlat), float(highlon)), (float(highlat), float(highlon)), (float(highlat), float(lowlon)), (float(lowlat), float(lowlon)))) if clazz: spaces = AirSpaces.objects.filter(geom__intersects=zone_bbox, clazz__in=clazz) else: spaces = AirSpaces.objects.filter(geom__intersects=zone_bbox) return spaces
def test_various_statuses(self): created = HttpCreated(location='http://example.com/thingy/1/') self.assertEqual(created.status_code, 201) self.assertEqual(created['Location'], 'http://example.com/thingy/1/') # Regression. created_2 = HttpCreated() self.assertEqual(created_2.status_code, 201) self.assertEqual(created_2['Location'], '') accepted = HttpAccepted() self.assertEqual(accepted.status_code, 202) no_content = HttpNoContent() self.assertEqual(no_content.status_code, 204) see_other = HttpSeeOther() self.assertEqual(see_other.status_code, 303) not_modified = HttpNotModified() self.assertEqual(not_modified.status_code, 304) bad_request = HttpBadRequest() self.assertEqual(bad_request.status_code, 400) unauthorized = HttpUnauthorized() self.assertEqual(unauthorized.status_code, 401) not_found = HttpNotFound() self.assertEqual(not_found.status_code, 404) not_allowed = HttpMethodNotAllowed() self.assertEqual(not_allowed.status_code, 405) conflict = HttpConflict() self.assertEqual(conflict.status_code, 409) gone = HttpGone() self.assertEqual(gone.status_code, 410) toomanyrequests = HttpTooManyRequests() self.assertEqual(toomanyrequests.status_code, 429) not_implemented = HttpNotImplemented() self.assertEqual(not_implemented.status_code, 501)
def get_detail(self, request, **kwargs): """ Called by the request dispatcher in case somebody tries to GET a job resource. For the frontend, deliver the current job status if pending, or the result. """ basic_bundle = self.build_bundle(request=request) try: job = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpNotFound() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") if job.done(): if job.exit_code == 0: response = {} # We deliver the columns layout for the result tables + all # global issues relative_url = reverse( 'results', kwargs={ 'api_name': 'front', 'pk': job.graph.pk, 'secret': job.secret}) # This is a quick fix for dealing with reverse() begind an SSL proxy # Normally, Django should consider the X-FORWARDED header inside the reverse() # implementation and figure out by itself what the correct base is results_url = settings.SERVER + relative_url if not job.requires_download: response['columns'] = [ {'mData': key, 'sTitle': title} for key, title in job.result_titles] response['axis_titles'] = job.axis_titles() response['static_info'] = job.static_info() try: response['issues'] = Result.objects.get( job=job, kind=Result.GRAPH_ISSUES).issues except Exception: # no global issues recorded, that's fine pass response = HttpResponse(json.dumps(response)) response["Location"] = results_url return response else: logger.debug("Job is done, but with non-zero exit code.") mail_managers( 'Job %s for graph %u ended with non-zero exit code %u.' % ( job.pk, job.graph.pk, job.exit_code), job.graph.to_xml()) return HttpApplicationError() else: # Job is pending, tell this by HTTP return code return HttpAccepted()
def get_probes(self, request, **kwargs): basic_bundle = self.build_bundle(request=request) try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpNotFound() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") try: character = Character.objects.get(pk=request.GET.get('character')) except Character.DoesNotExist: return HttpNotFound() result = obj.probe(character, request.GET.get('difficulty')) response = {"result": result} return HttpResponse(json.dumps(response), content_type='application/json')
def mine(self, request, *args, **kwargs): try: page = Homepage.objects.get(user=request.user) except Homepage.DoesNotExist: raise ImmediateHttpResponse(HttpNotFound()) bundle = self.build_bundle(obj=page, request=request) bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle)
def get_list(self, request, **kwargs): """ get_list """ try: resp = super(Resource, self).get_list(request, **kwargs) except ObjectDoesNotExist: return HttpNotFound() return resp
def obj_get_list(self, **kwargs): try: return super(RawModelResource, self).obj_get_list(**kwargs) except (NotFound, ObjectDoesNotExist): raise ImmediateHttpResponse(HttpNotFound(settings.HTTP_NOT_FOUND)) except ImmediateHttpResponse: raise except Exception: raise ImmediateHttpResponse( HttpApplicationError(settings.HTTP_APPLICATION_ERROR))
def userprofile(self, request, *args, **kwargs): fields = copy.copy(self._meta.fields) try: target_user = User.objects.get(pk=kwargs['pk']) except User.DoesNotExist: raise ImmediateHttpResponse(HttpNotFound()) else: if target_user == request.user: fields += ['first_name', 'last_name'] data = {k: getattr(target_user, k) for k in fields} return self.create_response(request, data)
def _get_object(self, kwargs, request, resource): if kwargs is None: kwargs = self._remove_api_resource_names( request.resolver_match.kwargs) del kwargs['request_type'] try: resource.cached_obj_get( bundle=resource.build_bundle(request=request), **kwargs) except queryset.DoesNotExist as e: logger.exception(e) raise ImmediateHttpResponse(response=HttpNotFound())
def obj_get(self, request, **kwargs): # We are expecting the pk to be 'agreement' so that are we not doing a # get on a list and all the tastypie baggage that provides. if kwargs['pk'] != 'agreement': raise ImmediateHttpResponse(response=HttpNotFound()) data = self.deserialize(request, request.raw_post_data, format='application/json') form = SBIForm(data) if not form.is_valid(): raise self.form_errors(form) res = self.client('GetSBIAgreement', form.bango_data) return SBIAgreement(terms(res.sbiAgreement), res.sbiAgreementValidFrom, None, None)
def post_detail( self, request, **kwargs ): repo = Repository.objects.get( mongo_id=kwargs.get( 'mongo_id' ) ) if repo is None: return HttpNotFound() bundle = self.build_bundle( request=request ) if not self.authorized_create_detail( repo, bundle ): return HttpUnauthorized() # TODO: the API doesn't accept JSON as a POST value since it's looking # in request.POST which is for form data. Instead, it should check for # data in either request.POST or it should run # json.loads(request.body) for JSON in the request body. new_id = repo.add_data( request.POST, request.FILES ) response_data = { 'success': True, 'id': str( new_id ) } return self.create_response( request, response_data )
def _get_obj_for_wrapped_view(self, request, **kwargs): """ Util function for custom views which are wrapped inside an object resource url. Returns a tuple with either the object which corresponds to the request, or an error response. """ basic_bundle = self.build_bundle(request=request) self.is_authenticated(request) try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return (None, HttpNotFound()) except MultipleObjectsReturned: return (None, HttpMultipleChoices("More than one resource is found at this URI.")) self.authorized_read_detail(self.get_object_list(basic_bundle.request), basic_bundle) return (obj, None)
def fetch_account(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) if not request.user.is_superuser: return HttpUnauthorized() data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) instance = None if 'uuid' in data: instance = get_user_by_related(data['uuid']) if instance is None and 'cif' in data and data['cif'] is not None: try: entity = Entity.objects.get(cif=data['cif']) instance = entity.user except Entity.DoesNotExist: try: person = Person.objects.get(nif=data['cif']) instance = person.user except Person.DoesNotExist: instance = None if instance is None and 'email' in data: instance = User.objects.filter(email=data['email']).first() if instance is None: instance = Person.objects.filter(email=data['email']).first() if instance is None: return HttpNotFound() response = gen_userwallet_data(instance) response['user'] = model_to_dict(instance) response['user']['is_registered'] = instance.is_registered() return self.create_response(request, response)
def password_reset(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self._get_json_request_data(request) deactivate = bool(data.get("deactivate", None)) basic_bundle = self.build_bundle(request=request) try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpNotFound() except MultipleObjectsReturned: return HttpMultipleChoices("More than one resource is found at this URI.") if deactivate: obj.disable_password() obj.password_reset() return self.create_response(request, { 'success': True, })
def obj_get(self, request, **kw): # Work around tastypie by not getting a list, but just # an object. With some data in the body. if kw['pk'] != 'status': raise ImmediateHttpResponse(response=HttpNotFound()) data = self.deserialize(request, request.raw_post_data, format='application/json') form = RefundStatusForm(data) if not form.is_valid(): raise self.form_errors(form) obj = form.cleaned_data['uuid'] try: res = self.client('GetRefundStatus', {'refundTransactionId': obj.uid_pay}, raise_on=(PENDING, CANT_REFUND, NOT_SUPPORTED), client=self.get_client(data)) code = res.responseCode except BangoFormError, exc: res = BangoResponse(exc.id, exc.message, '')
def obj_get(self, bundle, **kwargs): # No id transform to do as we are not using an unpredictable id with token suffix. if not issubclass(self._meta.object_class, UnpredictableIdMixin): return super(UnpredictableIdResourceMixin, self).obj_get(bundle, **kwargs) unpredictable_id = kwargs['pk'] obj_id, obj_token = UnpredictableIdMixin.split_unpredictable_id( unpredictable_id=unpredictable_id) kwargs['pk'] = obj_id obj = super(UnpredictableIdResourceMixin, self).obj_get(bundle, **kwargs) if obj._token != obj_token: Utils().logger().error( u"Invalid unpredictable id token ({unpredictable_id}).".format( unpredictable_id=unpredictable_id)) raise ImmediateHttpResponse(response=HttpNotFound()) return obj
def get_gpx(self, request, **kwargs): try: filename = kwargs.get('gpxid', None) dfilename = os.path.join("uploads", filename) track_geos = loadFromGpx(str(dfilename)) relief_profile = get_relief_profile_along_track(track_geos) except: raise ImmediateHttpResponse(response=HttpNotFound()) ib = get_space_intersect_path(track_geos) ib.indexes = [track_geos.project(Point(x)) for x in track_geos] ib.interpolated = [] ib.relief_profile = relief_profile bundle = self.build_bundle(obj=ib, request=request) bundle = self.full_dehydrate(bundle) bundle.data['success'] = True bundle.data['trackURL'] = '/static/' + filename self.log_throttled_access(request) return self.create_response(request, bundle)
def find_friend(self, request, **kwargs): """An endpoint that allows a user to request the location of their friend Does not allow users to request the location of people they're not friends with on facebook. Does not allow users to request the location of people who do not have a phone registered to their account (for push notifications) """ self._verify(request) data = self.deserialize(request, request.body, format=request.META.get( 'Content-Type', 'application/json')) # Was the Facebook ID of a friend supplied? friend_fb_id = data.get('friend_fb_id', None) if friend_fb_id is None: raise ImmediateHttpResponse( HttpBadRequest('Must specify a friend\'s FB ID')) # Does the requestor have a facebook account associated with their # profile? # # Should always be yes with the exception of the admin accounts my_user = request.user.social_auth.filter(provider='facebook') if not my_user.exists(): raise ImmediateHttpResponse( HttpForbidden('Could not find you as a facebook user')) # Does the friend have an account in our system? try: friend_user = UserSocialAuth.objects.get(provider='facebook', uid=friend_fb_id) except UserSocialAuth.DoesNotExist: msg = 'Could not find user with FB id {}'.format(friend_fb_id) raise ImmediateHttpResponse(HttpNotFound(msg)) # Are the requestor and the requested friend *actually* friends? graph = facebook.GraphAPI(access_token=my_user.first().tokens) response = graph.get_object('/me/friends/{}'.format(friend_fb_id)) if len(response['data']) == 0: msg = 'You can not request a location from that user' raise ImmediateHttpResponse(HttpForbidden(msg)) # Does the friend have a phone associated with their profile? # This should also always be yes, with the exception of the admins friend_devices = friend_user.user.userdevice_set.all() if not friend_devices.exists(): msg = 'Could not find friend with FB id {}'.format(friend_fb_id) raise ImmediateHttpResponse(HttpNotFound(msg)) # Send the request for location to the friend msg_data = { 'type': 'request_location', 'requestor': request.user.get_full_name(), 'requestor_id': request.user.pk } response_class = self._notify_user(friend_devices, msg_data) return self.create_response(request, data={}, response_class=response_class)