def post_list(self, request, **kwargs): """ Creates a new resource/object with the provided data. """ try: body = request.body except Exception: # pylint: disable=I0011,W0703 body = None deserialized = self.deserialize(request, body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def post_list(self, request, **kwargs): """ Exactly copied from https://github.com/toastdriven/django-tastypie/blob/v0.9.14/tastypie/resources.py#L1314 (BSD licensed) and modified to catch Exception and not returning traceback """ deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) try: updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location) except AssertionError as e: bundle.data['error_message'] = str(e) return self.create_response(request, bundle, response_class=http.HttpBadRequest)
def obj_create(self, bundle, **kwargs): request = bundle.request deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) if all([ k in deserialized for k in ['pnr', 'last_name', 'material_number'] ]): passenger, etickets, luggage = build_from_pnr_lastname_material_number( deserialized['pnr'], deserialized['last_name'], deserialized['material_number']) # if the luggage has correctly been saved, we can add a log # we take the flight from passenger eticket's first flight try: # TODO https://github.com/goujonpa/bagtrekkin/issues/30 # This should take into consideration flight dates # in etickets and take the closer flight from today flight = [ flight for e in etickets for flight in e.flights.order_by( 'flight_date', 'departure_time') ][0] except IndexError: raise IndexError( 'Application didn\'t find any flight for etickets.') Log.create(user=request.user, luggage=luggage, flight=flight) return http.HttpCreated() else: raise ValueError( 'Missing pnr and/or last_name and/or material_number.')
def post_list(self, request, **kwargs): deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) content_object = self.content_object.hydrate(bundle).obj obj = Accuracy.objects.filter( user=bundle.request.user, content_type=ContentType.objects.get_for_model(content_object), object_id=content_object.id) if obj.exists(): bundle = self.full_bundle(obj[0], bundle.request) super(AccuracyResource, self).obj_delete(bundle, **kwargs) return http.HttpNoContent() updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def put_detail(self, request, **kwargs): """ Either updates an existing resource or creates a new one with the provided data. Calls ``obj_update`` with the provided data first, but falls back to ``obj_create`` if the object does not already exist. If a new resource is created, return ``HttpCreated`` (201 Created). If ``Meta.always_return_data = True``, there will be a populated body of serialized data. If an existing resource is modified and ``Meta.always_return_data = False`` (default), return ``HttpNoContent`` (204 No Content). If an existing resource is modified and ``Meta.always_return_data = True``, return ``HttpAccepted`` (202 Accepted). """ fmt = request.META.get('CONTENT_TYPE', 'application/json') if fmt.startswith('multipart'): body = None else: body = request.body deserialized = self.deserialize(request, body, format=fmt) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) try: updated_bundle = self.obj_update( bundle=bundle, **self.remove_api_resource_names(kwargs)) if not self._meta.always_return_data: return http.HttpNoContent() else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpAccepted) except (NotFound, MultipleObjectsReturned): updated_bundle = self.obj_create( bundle=bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def post_account(self, request, **kwargs): """ Creates a new resource/object with the provided data. Calls ``obj_create`` with the provided data and returns a response with the new resource's location. If a new resource is created, return ``HttpCreated`` (201 Created). If ``Meta.always_return_data = True``, there will be a populated body of serialized data. """ ### start copied from tasytpie ### if django.VERSION >= (1, 4): body = request.body else: body = request.raw_post_data deserialized = self.deserialize(request, body, format=request.META.get('CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data(request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) ## start custom code ## user_bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) # create user and account account_resource = AccountResource() address_resource = AddressResource() event_resource = EventResource() user_resource = UserResource() updated_user_bundle = user_resource.obj_create(user_bundle, **kwargs) # update the bundle with the user and account, then call the regular order code bundle.data['user'] = user_resource.get_resource_uri(updated_user_bundle.obj) bundle.data['account'] = account_resource.get_resource_uri(updated_user_bundle.obj.account_set.all()[0]) updated_user_bundle.data['account'] = bundle.data['account'] try: # create the event updated_event_bundle = event_resource.obj_create(updated_user_bundle, **kwargs) bundle.data['event'] = event_resource.get_resource_uri(updated_event_bundle.obj) updated_event_bundle.data['event'] = bundle.data['event'] # create the location updated_location_bundle = address_resource.obj_create(updated_event_bundle, **kwargs) except: pass ## end custom code ## updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def post_list(self, request, **kwargs): deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data(request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs)) if not self._meta.always_return_data: return http.HttpCreated() else: return self.create_response(request, updated_bundle, response_class=http.HttpCreated)
def post_list(self, request, **kwargs): attachment_file = request.FILES['file'] upload_file_name = attachment_file.name att = Attachment.objects.create(source_filename=upload_file_name, creator=request.user, attachment_file=attachment_file) att.save() updated_bundle = self.full_bundle(obj=att, request=request) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def signup(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) try: self.validate_request(data, ['username', 'email', 'password']) user = User.objects.create_user( data.get("username"), data.get("email"), data.get("password") ) # Create an inactive user setattr(user, "is_active", False) user.save() # User used a invitation token if data.get("token", None) is not None: try: topicToken = TopicToken.objects.get(token=data.get("token")) # Add the user to the topic contributor group topicToken.topic.get_contributor_group().user_set.add(user) # Remove the token topicToken.delete() except TopicToken.DoesNotExist: # Failed silently if the token is unkown pass # Could we activate the new account by email? if settings.ACCOUNT_ACTIVATION_ENABLED: # Creates the activation key activation_key = self.get_activation_key(user.username) # Create the regisration profile rp = RegistrationProfile.objects.create(user=user, activation_key=activation_key) # Send the activation email rp.send_activation_email( RequestSite(request) ) # Output the answer return http.HttpCreated() except MalformedRequestError as e: return http.HttpBadRequest(e.message) except PermissionDenied as e: return http.HttpForbidden(e.message) except IntegrityError as e: return http.HttpForbidden("%s in request payload (JSON)" % e)
def post_detail(self, request, **kwargs): draw_id = kwargs['pk'] try: draw = self._client.retrieve_draw(draw_id) except mongodb.MongoDriver.NotFoundError: return http.HttpBadRequest("Draw not found") try: data = json.loads(request.body) except TypeError: data = json.loads(request.body.decode('utf-8')) if 'add_user' in data: if not draw.check_write_access(request.user): raise exceptions.ImmediateHttpResponse( response=http.HttpUnauthorized( "Only the owner can add users")) new_users = { str(user) for user in data['add_user'] if '@' in str(user) } new_users = [user for user in new_users if user not in draw.users] draw.users.extend(new_users) self._client.save_draw(draw) invite_user(new_users, draw) if 'remove_user' in data: if not draw.check_write_access(request.user): raise exceptions.ImmediateHttpResponse( response=http.HttpUnauthorized( "Only the owner can remove users")) try: draw.users.remove(str(data['remove_user'])) self._client.save_draw(draw) except ValueError: pass if request.user.is_authenticated( ) and request.user.pk not in draw.users: draw.users.append(request.user.pk) self._client.save_draw(draw) return http.HttpCreated()
def post_list(self, request, **kwargs): deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) data = dict_strip_unicode_keys(deserialized) if 'objects' not in data: raise BadRequest('Missing objects list.') if not data.get('objects'): raise BadRequest('Empty objects list.') base_bundle = self.build_bundle(request=request) supposed_objects = self.obj_get_list( bundle=base_bundle, **self.remove_api_resource_names(kwargs)) received_numbers = [ obj['material_number'] for obj in data.get('objects') ] received_filters = {'material_number__in': received_numbers} received_objects = self.get_object_list(request).filter( **received_filters) tp_objects = [ obj for obj in received_objects if obj in supposed_objects ] fn_objects = [ obj for obj in received_objects if obj not in supposed_objects ] fp_objects = [ obj for obj in supposed_objects if obj not in received_objects ] all_objects = {'tp': tp_objects, 'fn': fn_objects, 'fp': fp_objects} for status, objects in all_objects.iteritems(): for obj in objects: Log.create(user=request.user, luggage=obj, status=status) return http.HttpCreated()
def post_passwordreset(self, request, **kwargs): deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) location = self.get_resource_uri(bundle) # get the user user = User.objects.get(pk=kwargs['pk']) # whitelist check for url if ('url' in bundle.data.keys() and re.match( 'https?://(.+\.)?snapable\.com', bundle.data['url']) != None): user.send_password_reset(bundle.data['url']) elif ('url' in bundle.data.keys()): raise BadRequest( 'Invalid URL. Must be of type http(s)://*.snapable.com') return http.HttpCreated(location=location)
def _add_files_to_package(self, request, bundle, **kwargs): """ Adds a set of files to a package. The PUT body must be a list of zero or more JavaScript objects in the following format: { "relative_path": "string", "fileuuid": "string", "accessionid", "string", "sipuuid": "string", "origin": "string" } """ try: files_list = json.load(request) except ValueError: response = { "success": False, "error": "No JSON object could be decoded from POST body." } return http.HttpBadRequest(json.dumps(response), content_type="application/json") if not isinstance(files_list, list): response = { "success": False, "error": "JSON request must contain a list of objects." } return http.HttpBadRequest(json.dumps(response), content_type="application/json") property_map = { "relative_path": "name", "fileuuid": "source_id", "accessionid": "accessionid", "sipuuid": "source_package", "origin": "origin", } if len(files_list) == 0: return http.HttpResponse() created_files = [] for f in files_list: kwargs = {"package": bundle.obj} for source, dest in property_map.iteritems(): try: kwargs[dest] = f[source] except KeyError: response = { "success": False, "error": "File object was missing key: " + source } return http.HttpBadRequest(json.dumps(response), content_type="application_json") created_files.append(File(**kwargs)) for f in created_files: f.save() response = { "success": True, "message": "{} files created in package {}".format(len(created_files), bundle.obj.uuid) } return http.HttpCreated(json.dumps(response), content_type="application_json")
def post_list(self, request, **kwargs): """Attempt to redirect to QGIS Server Style management. A post method should have the following field: name: Slug name of style title: Title of style style: the style file uploaded Also, should have kwargs: layername or layer__name: The layer name associated with the style or layer__id: The layer id associated with the style """ from geonode.qgis_server.views import qml_style # Extract layer name information POST = request.POST FILES = request.FILES layername = POST.get('layername') or POST.get('layer__name') if not layername: layer_id = POST.get('layer__id') layer = Layer.objects.get(id=layer_id) layername = layer.name # move style file FILES['qml'] = FILES['style'] response = qml_style(request, layername) if isinstance(response, TemplateResponse): if response.status_code == 201: obj = QGISServerStyle.objects.get( layer_styles__layer__name=layername, name=POST['name']) updated_bundle = self.build_bundle(obj=obj, request=request) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response( request, updated_bundle, response_class=http.HttpCreated, location=location) else: context = response.context_data # Check form valid style_upload_form = context['style_upload_form'] if not style_upload_form.is_valid(): raise BadRequest(style_upload_form.errors.as_text()) alert_message = context['alert_message'] raise BadRequest(alert_message) elif isinstance(response, HttpResponse): response_class = None if response.status_code == 403: response_class = http.HttpForbidden return self.error_response(request, response.content, response_class=response_class)
def post_list(self, request, **kwargs): """ Creates a new resource/object with the provided data. Calls ``obj_create`` with the provided data and returns a response with the new resource's location. If a new resource is created, return ``HttpCreated`` (201 Created). If ``Meta.always_return_data = True``, there will be a populated body of serialized data. """ basic_bundle = self.build_bundle(request=request) deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) exclude_from_match = ['description', 'api_name'] # Build the item match terms for field, value in deserialized.iteritems(): print "field is", field if field not in exclude_from_match: kwargs[field] = value # If the object already exists then return it instead of creating a new one try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) bundle = self.build_bundle(obj=obj, request=request) bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle) except ObjectDoesNotExist: sys.exc_clear() except MultipleObjectsReturned: return http.HttpMultipleChoices( "More than one resource is found with these details.") bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) #raise Exception("I think we've gone far enough in post, don't you?") updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def post_list(self, request, **kwargs): """ Creates a new resource/object with the provided data. Calls ``obj_create`` with the provided data and returns a response with the new resource's location. If a new resource is created, return ``HttpCreated`` (201 Created). If ``Meta.always_return_data = True``, there will be a populated body of serialized data. """ basic_bundle = self.build_bundle(request=request) print "We're in post_list" print "Request is", request.body print "kwargs are", kwargs print "basic bundle is", basic_bundle.request deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) print "Deserialized is", deserialized # Populate search arguments search_fields = kwargs.copy() for field, value in deserialized.iteritems(): uri = None # Assign possible URIs to uri if type(value) is dict: uri = value.get('resource_uri', None) # Extract the id from foreign key resource uri if isinstance(uri, basestring) and field != 'resource_uri': related_id = re.search('/\w*/\w*/\w*/([0-9]*)', uri) if related_id and related_id.groups()[0]: search_fields[field] = int(related_id.groups()[0]) print "In deserialized field is %r, value is %r, id is %r" % ( field, value, related_id.groups()[0]) # If the object already exists then patch it instead of creating a new one try: obj = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(search_fields)) return self.patch_detail(request, obj=obj, **kwargs) except (ObjectDoesNotExist, MultipleObjectsReturned) as e: sys.exc_clear() #except MultipleObjectsReturned: # sys.exc_clear() # return http.HttpMultipleChoices("More than one resource is found with these details.") bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) #raise Exception("I think we've gone far enough in post, don't you?") print "kwargs are", kwargs updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def post_list(self, request, **kwargs): bundle = self.create_bundle(request) location = TablesResource().get_resource_uri(bundle) return http.HttpCreated(location=location)