def audit(self, request): """Performs an audit on a shelf based on location.""" self.check_xsrf_token(self.request_state) shelf = get_shelf(request.shelf_request) user_email = user.get_user_email() devices_on_shelf = [] shelf_string_query = 'shelf: {}'.format(shelf.key.urlsafe()) devices_retrieved_on_shelf = device_model.Device.search(shelf_string_query) for device_identifier in request.device_identifiers: device = device_model.Device.get(identifier=device_identifier) if not device: raise endpoints.NotFoundException( _DEVICE_DOES_NOT_EXIST_MSG % device_identifier) if device.shelf: if device.shelf == shelf.key: devices_on_shelf.append(device.key.urlsafe()) logging.info('Device %s is already on shelf.', device.serial_number) continue try: device.move_to_shelf(shelf=shelf, user_email=user_email) devices_on_shelf.append(device.key) except device_model.UnableToMoveToShelfError as err: raise endpoints.BadRequestException(str(err)) for device in devices_retrieved_on_shelf.results: if device.doc_id not in devices_on_shelf: api_utils.get_ndb_key(device.doc_id).get().remove_from_shelf( shelf=shelf, user_email=user_email) shelf.audit(user_email=user_email) return message_types.VoidMessage()
def _get_device(device_request): """Gets a device using any identifier, including identifier. If identifier is supplied, this will try it as both asset_tag and serial_number. Args: device_request: device_messages.DeviceRequest message. Returns: A device model, or None if one could not be found. Raises: endpoints.BadRequestException: if a supplied URL-safe key is invalid. endpoints.NotFoundException: if there is no such device, or there was an exception in getting the device. """ device_identifier = _get_identifier_from_request(device_request) if device_identifier == 'urlkey': device = api_utils.get_ndb_key(device_request.urlkey).get() else: device = device_model.Device.get( **{device_identifier: getattr(device_request, device_identifier)}) if not device: raise endpoints.NotFoundException( _NO_DEVICE_MSG % getattr(device_request, device_identifier)) return device
def associate_tag(self, user_email, tag_urlsafekey, more_info=None): """Associates a tag with a device. Args: user_email: str, the email of the user taking the action. tag_urlsafekey: str, the urlsafe representation of the ndb.Key for a tag. more_info: str, an informational field about a particular tag reference. """ tag_data = tag_model.TagData( tag=api_utils.get_ndb_key(tag_urlsafekey).get(), more_info=more_info) if tag_data not in self.tags: for device_tag in self.tags: if tag_urlsafekey == device_tag.tag.key.urlsafe(): # Updates more_info field of an existing associated tag. device_tag.more_info = more_info self.put() self.stream_to_bq( user_email, 'Updated more_info on tag %s to %s on device %s.' % (tag_data.tag.name, more_info, self.identifier)) return self.tags.append(tag_data) self.put() self.stream_to_bq( user_email, 'Associated tag %s with device %s' % (tag_data.tag.name, self.identifier))
def get(self, request): """Gets a tag by its urlsafe key.""" self.check_xsrf_token(self.request_state) tag = api_utils.get_ndb_key(request.urlsafe_key).get() return tag_messages.Tag(name=tag.name, hidden=tag.hidden, color=tag.color, protect=tag.protect, description=tag.description)
def submit(self, request): """Submits a response to a survey question.""" user_email = user_lib.get_user_email() question = api_utils.get_ndb_key( urlsafe_key=request.question_urlsafe_key).get() question.submit(acting_user=user_email, selected_answer=request.selected_answer, more_info_text=request.more_info_text) return message_types.VoidMessage()
def get_by_urlsafe_key(cls, urlsafe_key): """Gets a Tag by its urlsafe key. Args: urlsafe_key: str, the urlsafe encoding of the requested tag's ndb.Key. Returns: A Tag model entity. """ return api_utils.get_ndb_key(urlsafe_key).get()
def destroy(self, request): """Destroys a tag and removes all references via _pre_delete_hook method.""" self.check_xsrf_token(self.request_state) key = api_utils.get_ndb_key(urlsafe_key=request.urlsafe_key) tag = key.get() if tag.protect: raise endpoints.BadRequestException( 'Cannot destroy tag %s because it is protected.' % tag.name) key.delete() return message_types.VoidMessage()
def submit(self, request): """Submits a response to a survey question.""" user_email = user_lib.get_user_email() question = api_utils.get_ndb_key( urlsafe_key=request.question_urlsafe_key).get() selected_answer = survey_models.Answer.create( text=request.selected_answer.text, more_info_enabled=request.selected_answer.more_info_enabled, placeholder_text=request.selected_answer.placeholder_text) question.submit(acting_user=user_email, selected_answer=selected_answer, more_info_text=request.more_info_text) return message_types.VoidMessage()
def patch(self, request): """Patch a given survey question.""" self.check_xsrf_token(self.request_state) question = api_utils.get_ndb_key( urlsafe_key=request.question_urlsafe_key).get() answers = [] for answer in request.answers: try: new_answer = survey_models.Answer.create( text=answer.text, more_info_enabled=answer.more_info_enabled, placeholder_text=answer.placeholder_text) answers.append(new_answer) except ValueError as e: raise endpoints.BadRequestException(e.message) survey_kwargs = api_utils.to_dict(request, survey_models.Question) survey_kwargs['answers'] = answers question.patch(**survey_kwargs) return message_types.VoidMessage()
def update(self, request): """Updates an existing tag.""" self.check_xsrf_token(self.request_state) key = api_utils.get_ndb_key(urlsafe_key=request.tag.urlsafe_key) tag = key.get() if tag.protect: raise endpoints.BadRequestException( 'Cannot update tag %s because it is protected.' % tag.name) try: tag.update(user_email=user.get_user_email(), name=request.tag.name, hidden=request.tag.hidden, protect=request.tag.protect, color=request.tag.color, description=request.tag.description) except datastore_errors.BadValueError as err: raise endpoints.BadRequestException( 'Tag update failed due to: %s' % str(err)) return message_types.VoidMessage()
def get_shelf(request): """Gets a shelf using the location. Args: request: shelf_messages.ShelfRequest, the request message for a shelf. Returns: Shelf object. Raises: endpoints.NotFoundException when a shelf can not be found. """ if request.urlsafe_key: shelf = api_utils.get_ndb_key(request.urlsafe_key).get() else: shelf = shelf_model.Shelf.get(location=request.location) if not shelf: raise endpoints.NotFoundException( _SHELF_DOES_NOT_EXIST_MSG % request.location) return shelf
def list_devices(self, request): """Lists all devices based on any device attribute.""" self.check_xsrf_token(self.request_state) query, sort_options, returned_fields = ( search_utils.set_search_query_options(request.query)) if not query: shelf_query = '' if request.shelf: shelf_urlsafe_key = request.shelf.shelf_request.urlsafe_key if not shelf_urlsafe_key: shelf_urlsafe_key = shelf_api.get_shelf( request.shelf.shelf_request).key.urlsafe() request.shelf = None shelf_query = ':'.join(('shelf', shelf_urlsafe_key)) query = search_utils.to_query(request, device_model.Device) query = ' '.join((query, shelf_query)) cursor = search_utils.get_search_cursor(request.page_token) search_results = device_model.Device.search( query_string=query, query_limit=request.page_size, cursor=cursor, sort_options=sort_options, returned_fields=returned_fields) new_search_cursor = None if search_results.cursor: new_search_cursor = search_results.cursor.web_safe_string guest_permitted = config_model.Config.get('allow_guest_mode') messages = [] for document in search_results.results: device = api_utils.get_ndb_key(document.doc_id).get() messages.append( api_utils.build_device_message_from_model(device, guest_permitted)) return device_message.ListDevicesResponse( devices=messages, additional_results=bool(new_search_cursor), page_token=new_search_cursor)
def test_get_ndb_key_not_found(self): """Test the get of an ndb.Key, raises endpoints.BadRequestException.""" with self.assertRaisesRegexp(endpoints.BadRequestException, api_utils._CORRUPT_KEY_MSG): api_utils.get_ndb_key('corruptKey')
def destroy(self, request): """Destroys a tag and removes all references via _pre_delete_hook method.""" self.check_xsrf_token(self.request_state) api_utils.get_ndb_key(urlsafe_key=request.urlsafe_key).delete() return message_types.VoidMessage()