Python google.appengine.runtime.apiproxy_errors.ApplicationError() Examples

The following are code examples for showing how to use google.appengine.runtime.apiproxy_errors.ApplicationError(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: mlab-ns   Author: m-lab   File: file.py    Apache License 2.0 6 votes vote down vote up
def _make_call(method, request, response,
               deadline=30):
  """Perform File RPC call.

  Args:
    method: Service method name as string.
    request: Request protocol buffer.
    response: Response protocol buffer.
    deadline: Request deadline in seconds.

  Raises:
    Error or it's descendant if any File API specific error has happened.
  """

  rpc = _create_rpc(deadline=deadline)
  rpc.make_call(method, request, response)
  rpc.wait()
  try:
    rpc.check_success()
  except apiproxy_errors.ApplicationError, e:
    _raise_app_error(e) 
Example 2
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: channel.py    Apache License 2.0 6 votes vote down vote up
def _ToChannelError(error):
  """Translate an application error to a channel Error, if possible.

  Args:
    error: An ApplicationError to translate.

  Returns:
    The appropriate channel service error, if a match is found, or the original
    ApplicationError.
  """
  error_map = {
      channel_service_pb.ChannelServiceError.INVALID_CHANNEL_KEY:
        InvalidChannelClientIdError,
      channel_service_pb.ChannelServiceError.BAD_MESSAGE:
        InvalidMessageError,
      channel_service_pb.ChannelServiceError.APPID_ALIAS_REQUIRED:
        AppIdAliasRequired
      }

  if error.application_error in error_map:
    return error_map[error.application_error](error.error_detail)
  else:
    return error 
Example 3
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_GetHostname(self, request, response, request_id):
    if request.has_instance():
      instance = request.instance()
    else:
      instance = None
    try:
      module, version, dispatcher = self._GetModuleAndVersionFromRequest(
          request, request_id)
      response.set_hostname(dispatcher.get_hostname(module, version, instance))
    except (request_info.ModuleDoesNotExistError,
            request_info.VersionDoesNotExistError):
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_MODULE)
    except request_info.InvalidInstanceIdError:
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_INSTANCES) 
Example 4
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: datastore_admin.py    Apache License 2.0 6 votes vote down vote up
def _Call(call, req, resp):
  """Generic method for making a datastore API call.

  Args:
    call: string, the name of the RPC call
    req: the request PB. if the app_id field is not set, it defaults to the
      local app.
    resp: the response PB
  """
  if hasattr(req, 'app_id'):
    req.set_app_id(datastore_types.ResolveAppId(req.app_id()))

  try:
    result = apiproxy_stub_map.MakeSyncCall('datastore_v3', call, req, resp)
    if result:
      return result
    return resp
  except apiproxy_errors.ApplicationError, err:
    raise datastore._ToDatastoreError(err) 
Example 5
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    Apache License 2.0 6 votes vote down vote up
def _OpenImage(self, image):
    """Opens an image provided as a string.

    Args:
      image: Image data to be opened.

    Raises:
      ApplicationError: Image could not be opened or was an unsupported format.

    Returns:
      Image containing the image data passed in.
    """
    if not image:
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.NOT_IMAGE)

    image = StringIO.StringIO(image)
    try:
      return Image.open(image)
    except IOError:

      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.BAD_IMAGE_DATA) 
Example 6
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    Apache License 2.0 6 votes vote down vote up
def _ValidateCropArg(self, arg):
    """Check an argument for the Crop transform.

    Args:
      arg: float - Argument to Crop transform to check.

    Raises:
      ApplicationError: There was a problem with the provided argument.
    """
    if not isinstance(arg, float):
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)

    if 0 > arg or arg > 1.0:
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA) 
Example 7
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    Apache License 2.0 6 votes vote down vote up
def _Rotate(self, image, transform):
    """Use PIL to rotate the given image with the given transform.

    Args:
      image: PIL.Image.Image object to rotate.
      transform: images_service_pb.Transform to use when rotating.

    Returns:
      PIL.Image.Image with transforms performed on it.

    Raises:
      ApplicationError: Given data for the rotate was bad.
    """
    degrees = transform.rotate()
    if degrees < 0 or degrees % 90 != 0:
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
    degrees %= 360


    degrees = 360 - degrees
    return image.rotate(degrees) 
Example 8
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue.py    Apache License 2.0 6 votes vote down vote up
def purge(self):
    """Removes all the tasks in this Queue.

    This function takes constant time to purge a Queue and some delay may apply
    before the call is effective.

    Raises:
      UnknownQueueError if the Queue does not exist on server side.
    """
    request = taskqueue_service_pb.TaskQueuePurgeQueueRequest()
    response = taskqueue_service_pb.TaskQueuePurgeQueueResponse()

    request.set_queue_name(self.__name)
    if self._app:
      request.set_app_id(self._app)

    try:
      apiproxy_stub_map.MakeSyncCall('taskqueue',
                                     'PurgeQueue',
                                     request,
                                     response)
    except apiproxy_errors.ApplicationError, e:
      raise self.__TranslateError(e.application_error, e.error_detail) 
Example 9
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _DummyTaskStoreBulkAdd(self, request, response):
    """Adds tasks to the appropriate DummyTaskStore.

    Args:
      request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the
        tasks to add. N.B. all tasks in the request have been validated and
        those with empty names have been assigned unique names.
      response: The taskqueue_service_pb.TaskQueueBulkAddResponse to populate
        with the results. N.B. the chosen_task_name field in the response will
        not be filled-in.
    """
    store = self.GetDummyTaskStore(request.add_request(0).app_id(),
                                   request.add_request(0).queue_name())
    for add_request, task_result in zip(request.add_request_list(),
                                        response.taskresult_list()):
      try:
        store.Add(add_request)
      except apiproxy_errors.ApplicationError, e:
        task_result.set_result(e.application_error)
      else:
        task_result.set_result(taskqueue_service_pb.TaskQueueServiceError.OK) 
Example 10
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_UpdateQueue(self, request, unused_response):
    """Local implementation of the UpdateQueue RPC in TaskQueueService.

    Must adhere to the '_Dynamic_' naming convention for stubbing to work.
    See taskqueue_service.proto for a full description of the RPC.

    Args:
      request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest.
      unused_response: A taskqueue_service_pb.TaskQueueUpdateQueueResponse.
                       Not used.
    """
    queues = self._app_queues.setdefault(request.app_id(), {})
    if request.queue_name() in queues and queues[request.queue_name()] is None:
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_QUEUE)

    defensive_copy = self._QueueDetails()
    defensive_copy.CopyFrom(request)

    queues[request.queue_name()] = defensive_copy 
Example 11
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_DeleteQueue(self, request, response):
    """Local delete implementation of TaskQueueService.DeleteQueue.

    Args:
      request: A taskqueue_service_pb.TaskQueueDeleteQueueRequest.
      response: A taskqueue_service_pb.TaskQueueDeleteQueueResponse.
    """
    if not request.queue_name():
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME)

    queues = self._app_queues.get(request.app_id(), {})
    if request.queue_name() not in queues:
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE)
    elif queues[request.queue_name()] is None:
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_QUEUE)

    queues[request.queue_name()] = None 
Example 12
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_PauseQueue(self, request, response):
    """Local pause implementation of TaskQueueService.PauseQueue.

    Args:
      request: A taskqueue_service_pb.TaskQueuePauseQueueRequest.
      response: A taskqueue_service_pb.TaskQueuePauseQueueResponse.
    """
    if not request.queue_name():
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME)

    queues = self._app_queues.get(request.app_id(), {})
    if request.queue_name() != DEFAULT_QUEUE_NAME:
      if request.queue_name() not in queues:
        raise apiproxy_errors.ApplicationError(
            taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE)
      elif queues[request.queue_name()] is None:
        raise apiproxy_errors.ApplicationError(
            taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_QUEUE)

    queues[request.queue_name()].paused = request.pause() 
Example 13
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: blobstore.py    Apache License 2.0 6 votes vote down vote up
def _ToBlobstoreError(error):
  """Translates an application error to a datastore error, if possible.

  Args:
    error: An `ApplicationError` to translate.

  Returns:
    The `BlobstoreError` for the passed-in `ApplicationError`, if one is found.
    Otherwise, the original `ApplicationError` is returned.
  """
  error_map = {
      blobstore_service_pb.BlobstoreServiceError.INTERNAL_ERROR:
      InternalError,
      blobstore_service_pb.BlobstoreServiceError.BLOB_NOT_FOUND:
      BlobNotFoundError,
      blobstore_service_pb.BlobstoreServiceError.DATA_INDEX_OUT_OF_RANGE:
      DataIndexOutOfRangeError,
      blobstore_service_pb.BlobstoreServiceError.BLOB_FETCH_SIZE_TOO_LARGE:
      BlobFetchSizeTooLargeError,
      blobstore_service_pb.BlobstoreServiceError.PERMISSION_DENIED:
      PermissionDeniedError,
      }
  desired_exc = error_map.get(error.application_error)
  return desired_exc(error.error_detail) if desired_exc else error 
Example 14
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue.py    Apache License 2.0 6 votes vote down vote up
def purge(self):
    """Removes all of the tasks in this queue.

    Purging the queue takes time, regardless of the queue size. Tasks continue
    to run until the backends recognize that the queue has been purged. This
    operation is permanent; purged tasks cannot be recovered.

    Raises:
      Error-subclass on application errors.
    """
    request = taskqueue_service_pb.TaskQueuePurgeQueueRequest()
    response = taskqueue_service_pb.TaskQueuePurgeQueueResponse()

    request.set_queue_name(self.__name)
    if self._app:
      request.set_app_id(self._app)

    try:
      apiproxy_stub_map.MakeSyncCall('taskqueue',
                                     'PurgeQueue',
                                     request,
                                     response)
    except apiproxy_errors.ApplicationError, e:
      raise _TranslateError(e.application_error, e.error_detail) 
Example 15
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _TransactionalBulkAdd(self, request):
    """Uses datastore.AddActions to associate tasks with a transaction.

    Args:
      request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the
        tasks to add. N.B. all tasks in the request have been validated and
        assigned unique names.
    """
    try:



      apiproxy_stub_map.MakeSyncCall(
          'datastore_v3', 'AddActions', request, api_base_pb.VoidProto())
    except apiproxy_errors.ApplicationError, e:
      raise apiproxy_errors.ApplicationError(
          e.application_error +
          taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR,
          e.error_detail) 
Example 16
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def UpdateQueue_Rpc(self, request, response):
    """Implementation of the UpdateQueue RPC.

    Args:
      request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest.
      response: A taskqueue_service_pb.TaskQueueUpdateQueueResponse.
    """
    queue_name = request.queue_name()

    response = self._ValidateQueueName(queue_name)

    is_unknown_queue = (
        response == taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE)
    if response != taskqueue_service_pb.TaskQueueServiceError.OK and (
        not is_unknown_queue):
      raise apiproxy_errors.ApplicationError(response)

    if is_unknown_queue:
      self._queues[queue_name] = _Queue(request.queue_name())



      if self._app_id is not None:
        self._queues[queue_name].Populate(random.randint(10, 100))
    self._queues[queue_name].UpdateQueue_Rpc(request, response) 
Example 17
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def FetchTask_Rpc(self, request, response):
    """Implementation of the FetchTask RPC.

    Args:
      request: A taskqueue_service_pb.TaskQueueFetchTaskRequest.
      response: A taskqueue_service_pb.TaskQueueFetchTaskResponse.
    """
    task_name = request.task_name()
    pos = self._LocateTaskByName(task_name)
    if pos is None:
      if task_name in self.task_name_archive:
        error = taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_TASK
      else:
        error = taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_TASK
      raise apiproxy_errors.ApplicationError(error)

    _, task = self._sorted_by_name[pos]
    response.mutable_task().add_task().CopyFrom(task) 
Example 18
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_UpdateStorageLimit(self, request, response):
    """Local implementation of TaskQueueService.UpdateStorageLimit.

    Must adhere to the '_Dynamic_' naming convention for stubbing to work.
    See taskqueue_service.proto for a full description of the RPC.

    Args:
      request: A taskqueue_service_pb.TaskQueueUpdateStorageLimitRequest.
      response: A taskqueue_service_pb.TaskQueueUpdateStorageLimitResponse.
    """
    if _GetAppId(request) is None:
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.PERMISSION_DENIED)

    if request.limit() < 0 or request.limit() > 1000 * (1024 ** 4):
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.INVALID_REQUEST)

    response.set_new_limit(request.limit()) 
Example 19
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: _remote_socket_stub.py    Apache License 2.0 6 votes vote down vote up
def TranslateSystemErrors(method):
  """Decorator to catch and translate socket.error to ApplicationError.

  Args:
    method: An unbound method of APIProxyStub or a subclass.

  Returns:
    The method, altered such it catches socket.error, socket.timeout and
    socket.gaierror and re-raises the required apiproxy_errors.ApplicationError.
  """

  def WrappedMethod(self, *args, **kwargs):
    try:
      return method(self, *args, **kwargs)
    except socket.gaierror, e:
      raise apiproxy_errors.ApplicationError(
          RemoteSocketServiceError.GAI_ERROR,
          'system_error:%u error_detail:"%s"' % (e.errno, e.strerror))
    except socket.timeout, e:
      raise apiproxy_errors.ApplicationError(
          RemoteSocketServiceError.SYSTEM_ERROR,
          'system_error:%u error_detail:"%s"' % (errno.EAGAIN,
                                                 os.strerror(errno.EAGAIN))) 
Example 20
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: _remote_socket_stub.py    Apache License 2.0 6 votes vote down vote up
def _Dynamic_GetSocketOptions(self, request, response):
    state = self._LookupSocket(request.socket_descriptor())
    for opt in request.options_list():
      if (opt.level() ==
          remote_socket_service_pb.SocketOption.SOCKET_SOL_SOCKET and
          opt.option() ==
          remote_socket_service_pb.SocketOption.SOCKET_SO_ERROR):
        ret = response.add_options()
        ret.set_level(opt.level())
        ret.set_option(opt.option())
        ret.set_value(
            state.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR, 1024))
      else:
        value = self._mock_options.GetMockValue(opt.level(), opt.option())
        if value is None:
          raise apiproxy_errors.ApplicationError(
              RemoteSocketServiceError.PERMISSION_DENIED,
              'Attempt to get blocked socket option.')

        ret = response.add_options()
        ret.set_level(opt.level())
        ret.set_option(opt.option())
        ret.set_value(value) 
Example 21
Project: kay-template   Author: yosukesuzuki   File: gae_bulkloader.py    MIT License 5 votes vote down vote up
def _QueryForPbs(self, query):
    """Perform the given query and return a list of entity_pb's."""
    try:
      query_pb = query._ToPb(limit=self.batch_size)
      result_pb = datastore_pb.QueryResult()
      apiproxy_stub_map.MakeSyncCall('datastore_v3', 'RunQuery', query_pb,
                                     result_pb)
      next_pb = datastore_pb.NextRequest()
      next_pb.set_count(self.batch_size)
      next_pb.mutable_cursor().CopyFrom(result_pb.cursor())
      result_pb = datastore_pb.QueryResult()
      apiproxy_stub_map.MakeSyncCall('datastore_v3', 'Next', next_pb, result_pb)
      return result_pb.result_list()
    except apiproxy_errors.ApplicationError, e:
      raise datastore._ToDatastoreError(e) 
Example 22
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: users.py    Apache License 2.0 5 votes vote down vote up
def create_login_url(dest_url=None, _auth_domain=None,
                     federated_identity=None):
  """Computes the login URL for redirection.

  Args:
    dest_url: String that is the desired final destination URL for the user
        once login is complete. If `dest_url` does not specify a host, the host
        from the current request is used.
    federated_identity: Decommissioned, don't use. Setting this to a non-None
        value raises a NotAllowedError

  Returns:
       Login URL as a string. The login URL will use Google Accounts.

  Raises:
      NotAllowedError: If federated_identity is not None.
  """
  req = user_service_pb.CreateLoginURLRequest()
  resp = user_service_pb.CreateLoginURLResponse()
  if dest_url:
    req.set_destination_url(dest_url)
  else:
    req.set_destination_url('')
  if _auth_domain:
    req.set_auth_domain(_auth_domain)
  if federated_identity:
    raise NotAllowedError('OpenID 2.0 support is decomissioned')

  try:
    apiproxy_stub_map.MakeSyncCall('user', 'CreateLoginURL', req, resp)
  except apiproxy_errors.ApplicationError, e:
    if (e.application_error ==
        user_service_pb.UserServiceError.REDIRECT_URL_TOO_LONG):
      raise RedirectTooLongError
    elif (e.application_error ==
          user_service_pb.UserServiceError.NOT_ALLOWED):
      raise NotAllowedError
    else:
      raise e 
Example 23
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: users.py    Apache License 2.0 5 votes vote down vote up
def create_logout_url(dest_url, _auth_domain=None):
  """Computes the logout URL and specified destination URL for the request.

  This function works for Google Accounts applications.

  Args:
    dest_url: String that is the desired final destination URL for the user
        after the user has logged out. If `dest_url` does not specify a host,
        the host from the current request is used.

  Returns:
    Logout URL as a string.
  """
  req = user_service_pb.CreateLogoutURLRequest()
  resp = user_service_pb.CreateLogoutURLResponse()
  req.set_destination_url(dest_url)
  if _auth_domain:
    req.set_auth_domain(_auth_domain)

  try:
    apiproxy_stub_map.MakeSyncCall('user', 'CreateLogoutURL', req, resp)
  except apiproxy_errors.ApplicationError, e:
    if (e.application_error ==
        user_service_pb.UserServiceError.REDIRECT_URL_TOO_LONG):
      raise RedirectTooLongError
    else:
      raise e 
Example 24
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: channel_service_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_CreateChannel(self, request, response):
    """Implementation of channel.create_channel.

    Args:
      request: A ChannelServiceRequest.
      response: A ChannelServiceResponse
    """

    client_id = request.application_key()
    if not client_id:
      raise apiproxy_errors.ApplicationError(
          channel_service_pb.ChannelServiceError.INVALID_CHANNEL_KEY)

    if request.has_duration_minutes():
      duration = request.duration_minutes()
    else:
      duration = ChannelServiceStub.CHANNEL_TOKEN_DEFAULT_DURATION


    expiration_sec = long(self._time_func() + duration * 60) + 1

    raw_token = '-'.join([ChannelServiceStub.CHANNEL_TOKEN_IDENTIFIER,
                          str(random.randint(0, 2 ** 32)),
                          str(expiration_sec),
                          client_id])



    token = '-'.join([_GenerateTokenHash(raw_token), raw_token])

    self._log('Creating channel token %s with client id %s and duration %s',
              token, request.application_key(), duration)

    response.set_token(token) 
Example 25
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: channel_service_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_SendChannelMessage(self, request, response):
    """Implementation of channel.send_message.

    Queues a message to be retrieved by the client when it polls.

    Args:
      request: A SendMessageRequest.
      response: A VoidProto.
    """



    client_id = self.client_id_from_token(request.application_key())
    if client_id is None:
      client_id = request.application_key()

    if not request.message():
      raise apiproxy_errors.ApplicationError(
          channel_service_pb.ChannelServiceError.BAD_MESSAGE)

    if client_id in self._connected_channel_messages:
      self._log('Sending a message (%s) to channel with key (%s)',
                request.message(), client_id)
      self._connected_channel_messages[client_id].append(request.message())
    else:
      self._log('SKIPPING message (%s) to channel with key (%s): '
                'no clients connected',
                request.message(), client_id) 
Example 26
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: channel.py    Apache License 2.0 5 votes vote down vote up
def send_message(client_id, message):
  """Send a message to a channel.

  Args:
    client_id: The client id passed to create_channel.
    message: A string representing the message to send.

  Raises:
    InvalidChannelClientIdError: if client_id is not an instance of str or
        unicode, or if the (utf-8 encoded) string is longer than 64 characters.
    InvalidMessageError: if the message isn't a string or is too long.
    Errors returned by _ToChannelError
  """

  client_id = _ValidateClientId(client_id)

  if isinstance(message, unicode):
    message = message.encode('utf-8')
  elif not isinstance(message, str):
    raise InvalidMessageError('Message must be a string')

  if len(message) > MAXIMUM_MESSAGE_LENGTH:
    raise InvalidMessageError(
        'Message must be no longer than %d chars' % MAXIMUM_MESSAGE_LENGTH)

  request = channel_service_pb.SendMessageRequest()
  response = api_base_pb.VoidProto()

  request.set_application_key(client_id)
  request.set_message(message)

  try:
    apiproxy_stub_map.MakeSyncCall(_GetService(),
                                   'SendChannelMessage',
                                   request,
                                   response)
  except apiproxy_errors.ApplicationError, e:
    raise _ToChannelError(e) 
Example 27
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_GetVersions(self, request, response, request_id):
    module, dispatcher = self._GetModuleFromRequest(request, request_id)
    try:
      for version in dispatcher.get_versions(module):
        response.add_version(version)
    except request_info.ModuleDoesNotExistError:
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_MODULE) 
Example 28
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_GetDefaultVersion(self, request, response, request_id):
    module, dispatcher = self._GetModuleFromRequest(request, request_id)
    try:
      response.set_version(dispatcher.get_default_version(module))
    except request_info.ModuleDoesNotExistError:
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_MODULE) 
Example 29
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_GetNumInstances(self, request, response, request_id):
    try:
      module, version, dispatcher = self._GetModuleAndVersionFromRequest(
          request, request_id)
      response.set_instances(dispatcher.get_num_instances(module, version))
    except (request_info.ModuleDoesNotExistError,
            request_info.VersionDoesNotExistError,
            request_info.NotSupportedWithAutoScalingError):
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_VERSION) 
Example 30
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_SetNumInstances(self, request, response, request_id):
    try:
      module, version, dispatcher = self._GetModuleAndVersionFromRequest(
          request, request_id)
      dispatcher.set_num_instances(module, version, request.instances())
    except (request_info.ModuleDoesNotExistError,
            request_info.VersionDoesNotExistError,
            request_info.NotSupportedWithAutoScalingError):
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_VERSION) 
Example 31
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_StopModule(self, request, response, request_id):
    try:
      module, version, dispatcher = self._GetModuleAndVersionFromRequest(
          request, request_id)
      dispatcher.stop_version(module, version)
    except (request_info.ModuleDoesNotExistError,
            request_info.VersionDoesNotExistError,
            request_info.NotSupportedWithAutoScalingError):
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.INVALID_VERSION)
    except request_info.VersionAlreadyStoppedError:
      raise apiproxy_errors.ApplicationError(
          modules_service_pb.ModulesServiceError.UNEXPECTED_STATE) 
Example 32
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: modules.py    Apache License 2.0 5 votes vote down vote up
def _CheckAsyncResult(rpc,
                      expected_application_errors,
                      ignored_application_errors):
  try:
    rpc.check_success()
  except apiproxy_errors.ApplicationError, e:
    if e.application_error in ignored_application_errors:
      logging.info(ignored_application_errors.get(e.application_error))
      return
    if e.application_error in expected_application_errors:
      mapped_error = _MODULE_SERVICE_ERROR_MAP.get(e.application_error)
      if mapped_error:
        raise mapped_error()
    raise Error(e) 
Example 33
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: background_thread.py    Apache License 2.0 5 votes vote down vote up
def start_new_background_thread(target, args, kwargs=None):
  """Starts a new background thread.

  Creates a new background thread which will call target(*args, **kwargs).

  Args:
    target: A callable for the new thread to run.
    args: Position arguments to be passed to target.
    kwargs: Keyword arguments to be passed to target.

  Returns:
    The thread ID of the background thread.
  """

  if kwargs is None:
    kwargs = {}
  request = system_service_pb.StartBackgroundRequestRequest()
  response = system_service_pb.StartBackgroundRequestResponse()
  try:
    apiproxy_stub_map.MakeSyncCall('system', 'StartBackgroundRequest', request,
                                   response)
  except apiproxy_errors.ApplicationError as error:
    raise ERROR_MAP[error.application_error](error.error_detail)
  else:
    return background.EnqueueBackgroundThread(
        response.request_id(),
        target,
        args,
        kwargs) 
Example 34
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: datastore_file_stub.py    Apache License 2.0 5 votes vote down vote up
def __ReadPickled(self, filename):
    """Reads a pickled object from the given file and returns it.
    """
    self.__file_lock.acquire()

    try:
      try:
        if (filename and
            filename != '/dev/null' and
            os.path.isfile(filename) and
            os.stat(filename).st_size > 0):
          return pickle.load(open(filename, 'rb'))
        else:
          logging.warning('Could not read datastore data from %s', filename)
      except (AttributeError, LookupError, ImportError, NameError, TypeError,
              ValueError, struct.error, pickle.PickleError), e:


        raise apiproxy_errors.ApplicationError(
            datastore_pb.Error.INTERNAL_ERROR,
            'Could not read data from %s. Try running with the '
            '--clear_datastore flag. Cause:\n%r' % (filename, e))
    finally:
      self.__file_lock.release()

    return [] 
Example 35
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity.py    Apache License 2.0 5 votes vote down vote up
def _to_app_identity_error(error):
  """Translates an application error to an external error, if possible.

  Args:
    error: An `ApplicationError` to translate.

  Returns:
    error: The App Identity API-specific error message.
  """
  error_map = {
      app_identity_service_pb.AppIdentityServiceError.NOT_A_VALID_APP:
      InternalError,
      app_identity_service_pb.AppIdentityServiceError.DEADLINE_EXCEEDED:
      BackendDeadlineExceeded,
      app_identity_service_pb.AppIdentityServiceError.BLOB_TOO_LARGE:
      BlobSizeTooLarge,
      app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR:
      InternalError,
      app_identity_service_pb.AppIdentityServiceError.UNKNOWN_SCOPE:
      InvalidScope,
      app_identity_service_pb.AppIdentityServiceError.NOT_ALLOWED:
      NotAllowed,
      app_identity_service_pb.AppIdentityServiceError.NOT_IMPLEMENTED:
      OperationNotImplemented,
      }
  if error.application_error in error_map:
    return error_map[error.application_error](error.error_detail)
  else:
    return InternalError('%s: %s' %
                         (error.application_error, error.error_detail)) 
Example 36
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity.py    Apache License 2.0 5 votes vote down vote up
def make_sign_blob_call(rpc, bytes_to_sign):
  """Executes the RPC call to sign a blob.

  Args:
    rpc: A UserRPC instance.
    bytes_to_sign: Blob that must be signed.

  Returns:
    A tuple that contains the signing key name and the signature.

  Raises:
    TypeError: If `bytes_to_sign` is not a string.
  """
  if not isinstance(bytes_to_sign, str):
    raise TypeError('bytes_to_sign must be str: %s'
                    % bytes_to_sign)
  request = app_identity_service_pb.SignForAppRequest()
  request.set_bytes_to_sign(bytes_to_sign)
  response = app_identity_service_pb.SignForAppResponse()

  def signing_for_app_result(rpc):
    """Checks success, handles exceptions, and returns the converted RPC result.

    This method waits for the RPC if it has not yet finished and calls the
    post-call hooks on the first invocation.

    Args:
      rpc: A UserRPC object.

    Returns:
      A tuple that contains signing key name and signature.
    """
    assert rpc.service == _APP_IDENTITY_SERVICE_NAME, repr(rpc.service)
    assert rpc.method == _SIGN_FOR_APP_METHOD_NAME, repr(rpc.method)
    try:
      rpc.check_success()
    except apiproxy_errors.ApplicationError, err:
      raise _to_app_identity_error(err)

    return (response.key_name(), response.signature_bytes()) 
Example 37
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity.py    Apache License 2.0 5 votes vote down vote up
def make_get_public_certificates_call(rpc):
  """Executes the RPC call to get a list of public certificates.

  Args:
    rpc: A UserRPC instance.

  Returns:
    A list of `PublicCertificate` objects.
  """
  request = app_identity_service_pb.GetPublicCertificateForAppRequest()
  response = app_identity_service_pb.GetPublicCertificateForAppResponse()

  def get_certs_result(rpc):
    """Checks success, handles exceptions, and returns the converted RPC result.

    This method waits for the RPC if it has not yet finished and calls the
    post-call hooks on the first invocation.

    Args:
      rpc: A UserRPC object.

    Returns:
      A list of `PublicCertificate` objects.
    """
    assert rpc.service == _APP_IDENTITY_SERVICE_NAME, repr(rpc.service)
    assert rpc.method == _GET_CERTS_METHOD_NAME, repr(rpc.method)
    try:
      rpc.check_success()
    except apiproxy_errors.ApplicationError, err:
      raise _to_app_identity_error(err)
    result = []
    for cert in response.public_certificate_list_list():
      result.append(PublicCertificate(
          cert.key_name(), cert.x509_certificate_pem()))
    return result 
Example 38
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity.py    Apache License 2.0 5 votes vote down vote up
def make_get_default_gcs_bucket_name_call(rpc):
  """Gets the default Google Cloud Storage bucket name for the app.

  Args:
    rpc: A UserRPC object.

  Returns:
    The default Google Cloud Storage bucket name for the app.
  """
  request = app_identity_service_pb.GetDefaultGcsBucketNameRequest()
  response = app_identity_service_pb.GetDefaultGcsBucketNameResponse()

  if rpc.deadline is not None:
    request.set_deadline(rpc.deadline)

  def get_default_gcs_bucket_name_result(rpc):
    """Checks success, handles exceptions, and returns the converted RPC result.

    This method waits for the RPC if it has not yet finished and calls the
    post-call hooks on the first invocation.

    Args:
      rpc: A UserRPC object.

    Returns:
      A string of the name of the app's default Google Cloud Storage bucket.
    """
    assert rpc.service == _APP_IDENTITY_SERVICE_NAME, repr(rpc.service)
    assert rpc.method == _GET_DEFAULT_GCS_BUCKET_NAME_METHOD_NAME, (
        repr(rpc.method))
    try:
      rpc.check_success()
    except apiproxy_errors.ApplicationError, err:
      raise _to_app_identity_error(err)

    return response.default_gcs_bucket_name() or None 
Example 39
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity_defaultcredentialsbased_stub.py    Apache License 2.0 5 votes vote down vote up
def _PopulateX509(self):
    with self._x509_init_lock:
      if self._x509 is None:

        url = ('https://www.googleapis.com/service_accounts/v1/metadata/x509/%s'
               % urllib.unquote_plus(self._credentials.service_account_email))
        response = urlfetch.fetch(
            url=url,
            validate_certificate=True,
            method=urlfetch.GET)
        if response.status_code != 200:
          raise apiproxy_errors.ApplicationError(
              app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
              'Unable to load X509 cert: %s Response code: %i, Content: %s' % (
                  url, response.status_code, response.content))

        message = 'dummy'
        _, signature = self._credentials.sign_blob(message)

        for signing_key, x509 in json.loads(response.content).items():
          der = rsa.pem.load_pem(x509, 'CERTIFICATE')
          asn1_cert, _ = decoder.decode(der, asn1Spec=Certificate())

          key_bitstring = (
              asn1_cert['tbsCertificate']
              ['subjectPublicKeyInfo']
              ['subjectPublicKey'])
          key_bytearray = BitStringToByteString(key_bitstring)

          public_key = rsa.PublicKey.load_pkcs1(key_bytearray, 'DER')
          try:
            if rsa.pkcs1.verify(message, signature, public_key):
              self._x509 = x509
              self._signing_key = signing_key
              return
          except rsa.pkcs1.VerificationError:
            pass

        raise apiproxy_errors.ApplicationError(
            app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
            'Unable to find matching X509 cert for private key: %s' % url) 
Example 40
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: app_identity_defaultcredentialsbased_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_GetAccessToken(self, request, response):
    """Implementation of AppIdentityService::GetAccessToken.

    This API requires internet access.

    Raises:
      apiproxy_errors.ApplicationError: If unexpected response from
                                        Google server.
    """
    scope = ' '.join(request.scope_list())
    with self._access_token_cache_lock:
      rv = self._access_token_cache.get(scope, None)
    now = int(time.time())

    if not (rv and rv['expires'] > (now + 60)):
      credentials = self._credentials
      if credentials.create_scoped_required():
        credentials = credentials.create_scoped(request.scope_list())
      token = credentials.get_access_token()
      rv = {
          'access_token': token.access_token,
          'expires': now + token.expires_in,
      }
      with self._access_token_cache_lock:
        self._access_token_cache[scope] = rv

    response.set_access_token(rv['access_token'])
    response.set_expiration_time(rv['expires']) 
Example 41
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def _ToImagesError(error, blob_key=None):
  """Translates an application error to an Images error, if possible.

  Args:
    error: An `ApplicationError` to translate.
    blob_key: The `blob_key` that is used in the function that caused the
        error. Set this argument to `None` if the blob key is unknown.

  Returns:
    An Images API error if one is found; all other errors are returned as-is.
  """
  error_map = {
      images_service_pb.ImagesServiceError.NOT_IMAGE:
      NotImageError,
      images_service_pb.ImagesServiceError.BAD_IMAGE_DATA:
      BadImageError,
      images_service_pb.ImagesServiceError.IMAGE_TOO_LARGE:
      LargeImageError,
      images_service_pb.ImagesServiceError.INVALID_BLOB_KEY:
      InvalidBlobKeyError,
      images_service_pb.ImagesServiceError.ACCESS_DENIED:
      AccessDeniedError,
      images_service_pb.ImagesServiceError.OBJECT_NOT_FOUND:
      ObjectNotFoundError,
      images_service_pb.ImagesServiceError.UNSPECIFIED_ERROR:
      TransformationError,
      images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA:
      BadRequestError,
      }

  error_code = error.application_error

  if error_code == images_service_pb.ImagesServiceError.INVALID_BLOB_KEY:
    return InvalidBlobKeyError(blob_key)

  desired_exc = error_map.get(error_code, Error)
  return desired_exc(error.error_detail) 
Example 42
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def delete_serving_url_async(blob_key, rpc=None):
  """Deletes a serving URL created using get_serving_url - async version.

  Args:
    blob_key: `BlobKey`, `BlobInfo`, string, or unicode representation of the
        BlobKey of a blob with an existing URL that you want to delete.
    rpc: Optional UserRPC object.

  Returns:
    A UserRPC object.

  Raises:
    BlobKeyRequiredError: If no `blob_key` was specified.
    InvalidBlobKeyError: If the `blob_key` supplied was invalid.
    Error: There was a generic error deleting the serving URL.
  """
  if not blob_key:
    raise BlobKeyRequiredError("A Blobkey is required for this operation.")

  request = images_service_pb.ImagesDeleteUrlBaseRequest()
  response = images_service_pb.ImagesDeleteUrlBaseResponse()

  request.set_blob_key(_extract_blob_key(blob_key))

  def delete_serving_url_hook(rpc):
    """Checks success, handles exceptions, and returns the converted RPC result.

    Args:
      rpc: A UserRPC object.

    Raises:
      See `delete_serving_url_async` for more details.
    """
    try:
      rpc.check_success()
    except apiproxy_errors.ApplicationError, e:
      raise _ToImagesError(e, blob_key) 
Example 43
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_Histogram(self, request, response):
    """Trivial implementation of an API.

    Based off documentation of the PIL library at
    http://www.pythonware.com/library/pil/handbook/index.htm

    Args:
      request: ImagesHistogramRequest - Contains the image.
      response: ImagesHistogramResponse - Contains histogram of the image.

    Raises:
      ApplicationError: Image was of an unsupported format.
    """
    image = self._OpenImageData(request.image())

    img_format = image.format
    if img_format not in FORMAT_LIST:
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.NOT_IMAGE)
    image = image.convert(RGBA)
    red = [0] * 256
    green = [0] * 256
    blue = [0] * 256




    for pixel in image.getdata():
      red[int((pixel[0] * pixel[3]) / 255)] += 1
      green[int((pixel[1] * pixel[3]) / 255)] += 1
      blue[int((pixel[2] * pixel[3]) / 255)] += 1
    histogram = response.mutable_histogram()
    for value in red:
      histogram.add_red(value)
    for value in green:
      histogram.add_green(value)
    for value in blue:
      histogram.add_blue(value) 
Example 44
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    Apache License 2.0 5 votes vote down vote up
def _OpenImageData(self, image_data):
    """Open image data from ImageData protocol buffer.

    Args:
      image_data: ImageData protocol buffer containing image data or blob
        reference.

    Returns:
      Image containing the image data passed in or reference by blob-key.

    Raises:
      ApplicationError: Both content and blob-key are provided.
      NOTE: 'content' must always be set because it is a required field,
      however, it must be the empty string when a blob-key is provided.
    """
    if image_data.content() and image_data.has_blob_key():
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.INVALID_BLOB_KEY)

    if image_data.has_blob_key():
      image = self._OpenBlob(image_data.blob_key())
    else:
      image = self._OpenImage(image_data.content())


    img_format = image.format
    if img_format not in FORMAT_LIST:
      raise apiproxy_errors.ApplicationError(
          images_service_pb.ImagesServiceError.NOT_IMAGE)
    return image 
Example 45
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: search.py    Apache License 2.0 5 votes vote down vote up
def get_result(self):
    self._rpc.wait()
    try:
      self._rpc.check_success()
    except apiproxy_errors.ApplicationError, e:
      raise _ToSearchError(e) 
Example 46
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: search.py    Apache License 2.0 5 votes vote down vote up
def _MakeSyncSearchServiceCall(call, request, response, deadline):
  """Deprecated: Make a synchronous call to search service.

  If the deadline is not None, waits only until the deadline expires.

  Args:
    call: Method name to call, as a string
    request: The request object
    response: The response object

  Kwargs:
    deadline: Deadline for RPC call in seconds; if None use the default.

  Raises:
    TypeError: if the deadline is not a number and is not None.
    ValueError: If the deadline is less than zero.
  """
  _ValidateDeadline(deadline)
  logging.warning('_MakeSyncSearchServiceCall is deprecated; please use API.')
  try:
    if deadline is None:
      apiproxy_stub_map.MakeSyncCall('search', call, request, response)
    else:


      rpc = apiproxy_stub_map.UserRPC('search', deadline=deadline)
      rpc.make_call(call, request, response)
      rpc.wait()
      rpc.check_success()
  except apiproxy_errors.ApplicationError, e:
    raise _ToSearchError(e) 
Example 47
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue.py    Apache License 2.0 5 votes vote down vote up
def __AddTasks(self, tasks, transactional):
    """Internal implementation of .add() where tasks must be a list."""

    if len(tasks) > MAX_TASKS_PER_ADD:
      raise TooManyTasksError(
          'No more than %d tasks can be added in a single add call' %
          MAX_TASKS_PER_ADD)

    request = taskqueue_service_pb.TaskQueueBulkAddRequest()
    response = taskqueue_service_pb.TaskQueueBulkAddResponse()

    task_names = set()
    for task in tasks:
      if task.name:
        if task.name in task_names:
          raise DuplicateTaskNameError(
              'The task name %r is used more than once in the request' %
              task.name)
        task_names.add(task.name)

      self.__FillAddRequest(task, request.add_add_request(), transactional)

    try:
      apiproxy_stub_map.MakeSyncCall('taskqueue', 'BulkAdd', request, response)
    except apiproxy_errors.ApplicationError, e:
      raise self.__TranslateError(e.application_error, e.error_detail) 
Example 48
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 5 votes vote down vote up
def Add(self, request):
    """Inserts a new task into the store.

    Args:
      request: A taskqueue_service_pb.TaskQueueAddRequest.

    Raises:
      apiproxy_errors.ApplicationError: If a task with the same name is already
      in the store.
    """

    pos = bisect.bisect_left(self._sorted_by_name, (request.task_name(),))
    if (pos < len(self._sorted_by_name) and
        self._sorted_by_name[pos][0] == request.task_name()):
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.TASK_ALREADY_EXISTS)

    now = datetime.datetime.utcnow()
    now_sec = time.mktime(now.timetuple())
    task = taskqueue_service_pb.TaskQueueQueryTasksResponse_Task()
    task.set_task_name(request.task_name())
    task.set_eta_usec(request.eta_usec())
    task.set_creation_time_usec(now_sec * 1e6)
    task.set_url(request.url())
    task.set_method(request.method())
    for keyvalue in task.header_list():
      header = task.add_header()
      header.set_key(keyvalue.key())
      header.set_value(keyvalue.value())
    if request.has_description():
      task.set_description(request.description())
    if request.has_body():
      task.set_body(request.body())
    if request.has_crontimetable():
      task.mutable_crontimetable().set_schedule(
          request.crontimetable().schedule())
      task.mutable_crontimetable().set_timezone(
          request.crontimetable().timezone())
    self._InsertTask(task) 
Example 49
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_Add(self, request, response):
    bulk_request = taskqueue_service_pb.TaskQueueBulkAddRequest()
    bulk_response = taskqueue_service_pb.TaskQueueBulkAddResponse()

    bulk_request.add_add_request().CopyFrom(request)
    self._Dynamic_BulkAdd(bulk_request, bulk_response)

    assert bulk_response.taskresult_size() == 1
    result = bulk_response.taskresult(0).result()

    if result != taskqueue_service_pb.TaskQueueServiceError.OK:
      raise apiproxy_errors.ApplicationError(result)
    elif bulk_response.taskresult(0).has_chosen_task_name():
      response.set_chosen_task_name(
          bulk_response.taskresult(0).chosen_task_name()) 
Example 50
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: taskqueue_stub.py    Apache License 2.0 5 votes vote down vote up
def _Dynamic_PurgeQueue(self, request, response):
    """Local purge implementation of TaskQueueService.PurgeQueue.

    Args:
      request: A taskqueue_service_pb.TaskQueuePurgeQueueRequest.
      response: A taskqueue_service_pb.TaskQueuePurgeQueueResponse.
    """
    if not request.queue_name():
      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME)

    if request.has_app_id():
      queues = self._app_queues.get(request.app_id(), {})
      if request.queue_name() != DEFAULT_QUEUE_NAME:
        if request.queue_name() not in queues:
          raise apiproxy_errors.ApplicationError(
              taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE)
        elif queues[request.queue_name()] is None:
          raise apiproxy_errors.ApplicationError(
              taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_QUEUE)

      store = self.GetDummyTaskStore(request.app_id(), request.queue_name())
      for task in store.Lookup(store.Count()):
        store.Delete(task.task_name())
    elif (not self._IsValidQueue(request.queue_name(), None)
          and not request.queue_name() in self._taskqueues):


      raise apiproxy_errors.ApplicationError(
          taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE)

    self.FlushQueue(request.queue_name())