def invite(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) email = data.get('email', '') if not email: return HttpBadRequest() try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) account = self.cached_obj_get( bundle=bundle, **self.remove_api_resource_names(kwargs)) invite = GuestInvitation.objects.invite_user(account=account, email=email) return self.create_response(request, {'token': invite.token}, response_class=HttpCreated) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.")
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 get_grafana_line(self, request, **kwargs): self.method_check(request, allowed=['get', 'options']) self.is_authenticated(request) response = HttpResponse() response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = 'Content-Type' if request.method == 'options': return response try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") response.content = '<h2>{}</h2><span>FDID: {} STATE: {} POPULATION: {}</span>'.format( obj.name, obj.fdid, obj.state, obj.population) return response
def get_subcategory_detail(self, request, **kwargs): """Get the SubcategorySubmission for the Subcategory where id = kwargs['subcatpk'].""" # Need to check SubcategorySubmissionResource.Meta.allowed_methods # explicitly because the URL fiddling done above # bypasses the usual check: if (request.method.lower() not in SubcategorySubmissionResource.Meta.allowed_methods): return HttpMethodNotAllowed() self.is_authenticated(request) subcategory_id = kwargs.pop('subcatpk') # Make sure the submission set is valid: 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 HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") kwargs['subcatpk'] = subcategory_id kwargs['submissionset'] = obj return SubcategorySubmissionResource().get_detail(request, **kwargs)
def get_credit_detail(self, request, **kwargs): """Get the CreditSubmissionResource that matches the Credit where id = kwargs['credpk'] and the SubmissionSet where id = kwargs['pk']. """ # Need to check CreditSubmissionResource.Meta.allowed_methods # explicitly because the URL fiddling done above # bypasses the usual check: if (request.method.lower() not in CreditSubmissionResource.Meta.allowed_methods): return HttpMethodNotAllowed() self.is_authenticated(request) credit_id = kwargs.pop('credpk') basic_bundle = self.build_bundle(request=request) try: submissionset = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") kwargs.pop('pk') kwargs['credpk'] = credit_id kwargs['submissionset'] = submissionset credit_submission_resource = CreditSubmissionResource() detail = credit_submission_resource.get_detail(request, **kwargs) return detail
def purchase(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) amount = data.get('amount', '') if not amount: return HttpBadRequest() try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) account = self.cached_obj_get( bundle=bundle, **self.remove_api_resource_names(kwargs)) card_payment = PendingPayment.objects.currency_purchase( account, amount) return self.create_response(request, { 'reference': card_payment.reference, 'url': settings.BASESITE_URL + reverse('payments:payment_form', kwargs={'uuid': card_payment.reference}) }, response_class=HttpCreated) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.")
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_children(self, request, **kwargs): try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices("More than one resource is found at this URI") child_resource = Facebook_Status_CommentResource() return child_resource.get_list(request, parent_id=obj.pk)
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 remove_children(self, request, **kwargs): try: obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices("More than one resource " "is found at this URI.") if request.method == 'POST': data = json.loads(request.POST.items()[0][0]) if 'image' in data: if isinstance(data['image'], list): for URI in data['image']: try: im = Image.objects.get( uuid=uuid_re.search(URI).group() ) obj.image_set.remove(im) except ObjectDoesNotExist: return HttpResponseNotFound( 'At least one of the image ' 'URI\'s cannot be found') else: raise ImmediateHttpResponse(response=HttpForbidden( 'Image URI\'s must be in an array')) if 'wordbox' in data: if isinstance(data['wordbox'], list): for URI in data['wordbox']: try: wb = WordBox.objects.get(uuid=uuid_re.search( URI).group()) obj.wordbox_set.remove(wb) except ObjectDoesNotExist: return HttpResponseNotFound( 'At least one of the wordbox ' 'URI\'s cannot be found') else: raise ImmediateHttpResponse(response=HttpForbidden( 'Wordbox URI\'s must be in an array')) else: raise ImmediateHttpResponse(response=HttpResponse(status=405)) return HttpCreated()
def get_offers(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") offers = OffersResource() return offers.get_list(request, entity=obj.pk)
def handle_nested(self, request, **kwargs): resource_name = kwargs.pop('nest_resource') resource = self.fields[resource_name].to_class().__class__ try: stripped_kwargs = self.remove_api_resource_names(kwargs) obj = self.cached_obj_get(request=request, **stripped_kwargs) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices('Multiple objects with this PK.') r = resource() if request.method.lower() == 'get': return r.get_list(request, report=obj.pk) elif request.method.lower() == 'post': cont_type = request.META.get('CONTENT_TYPE', 'application/json') deserialized = r.deserialize(request, format=cont_type) report_uri = ReportResource().get_resource_uri(obj) user_uri = UserResource().get_resource_uri(request.user) parms = {'report': report_uri, 'user': user_uri} if 'form' in cont_type: deserialized = dict( (str(k), v[0] if (type(v)==list and len(v)>0) else v) \ for k, v in deserialized.iteritems()) parms.update(deserialized) try: bundle = r.build_bundle(data=dict_strip_unicode_keys(parms), request=request) r.is_valid(bundle, request) r.obj_create(bundle) # this creates the actual child except: raise ValueError(parms) bundle_dehyd = r.full_dehydrate(bundle) resp = r.create_response(request, bundle_dehyd) resp['location'] = r.get_resource_uri(bundle) resp.status_code = 201 return resp else: raise NotImplementedError('In POST and GET we trust.')
def cancel_payment(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) payment = self.cached_obj_get( bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") payment.cancel_payment() return self.create_response(request, bundle, response_class=HttpCreated)
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 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 get_category_list(self, request, **kwargs): """Get a list of categories for the SubmissionSet with id = kwargs['pk'].""" # Need to check CategorySubmissionResource.Meta.allowed_methods # explicitly because the URL fiddling done above # bypasses the usual check: if (request.method.lower() not in CategorySubmissionResource.Meta.allowed_methods): return HttpMethodNotAllowed() self.is_authenticated(request) 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 HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") category_submission_resource = CategorySubmissionResource() return category_submission_resource.get_list(request, submissionset=obj.pk)
def obj_get(self, bundle, **kwargs): handle_id = int(kwargs.get('pk')) q = """ MATCH (h:Host {handle_id: {handle_id}})<-[r:Depends_on]-(s:Host_Service) WHERE h.operational_state <> 'Decommissioned' AND r.state CONTAINS 'open' AND r.noclook_last_seen > {last_seen} RETURN h.handle_id as handle_id, h.ip_addresses as ip_addresses, collect(distinct r.protocol + r.port) as ports """ host_list = nc.query_to_list(nc.graphdb.manager, q, handle_id=handle_id, last_seen=self.last_seen()) if len(host_list) == 0: raise NotFound( 'HostScan object not found with handle_id: {}'.format( handle_id)) if len(host_list) > 1: raise HttpMultipleChoices( 'Found {} HostScan objects with handle_id: {}'.format( len(host_list), handle_id)) return HostScan(host_list[0])
def get_relationships(self, request, **kwargs): rel_type = kwargs.get('rel_type', None) if rel_type: kwargs.pop('rel_type', None) try: data = {'pk': kwargs['pk']} if getattr(self._meta, 'pk_field', 'pk') != 'pk': kwargs[self._meta.pk_field] = kwargs['pk'] data = {self._meta.pk_field: kwargs['pk']} kwargs.pop('pk', None) bundle = self.build_bundle(data, request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) kwargs = {'parent_obj': obj.pk} except ObjectDoesNotExist: return HttpGone() except MultipleObjectsReturned: return HttpMultipleChoices( "More than one resource is found at this URI.") if rel_type: kwargs['rel_type'] = rel_type child_resource = RelationshipResource() return child_resource.get_list(request, **kwargs)