Beispiel #1
0
def _datastore_begin_transaction(read_only, retries=None, timeout=None):
    """Calls ``BeginTransaction`` on Datastore.

    Args:
        read_only (bool): Whether to start a read-only or read-write
            transaction.
        retries (int): Number of times to potentially retry the call. If
            :data:`None` is passed, will use :data:`_retry._DEFAULT_RETRIES`.
            If :data:`0` is passed, the call is attempted only once.
        timeout (float): Timeout, in seconds, to pass to gRPC call. If
            :data:`None` is passed, will use :data:`_DEFAULT_TIMEOUT`.

    Returns:
        tasklets.Tasklet: A future for
            :class:`google.cloud.datastore_v1.datastore_pb2.BeginTransactionResponse`
    """
    client = context_module.get_context().client
    if read_only:
        options = datastore_pb2.TransactionOptions(
            read_only=datastore_pb2.TransactionOptions.ReadOnly())
    else:
        options = datastore_pb2.TransactionOptions(
            read_write=datastore_pb2.TransactionOptions.ReadWrite())

    request = datastore_pb2.BeginTransactionRequest(
        project_id=client.project, transaction_options=options)

    return make_call("BeginTransaction",
                     request,
                     retries=retries,
                     timeout=timeout)
Beispiel #2
0
    def test_begin_transaction(self):
        from google.cloud.datastore_v1.proto import datastore_pb2

        project = "PROJECT"
        transaction = b"TRANSACTION"
        rsp_pb = datastore_pb2.BeginTransactionResponse()
        rsp_pb.transaction = transaction

        # Create mock HTTP and client with response.
        http = _make_requests_session(
            [_make_response(content=rsp_pb.SerializeToString())]
        )
        client_info = _make_client_info()
        client = mock.Mock(
            _http=http,
            _base_url="test.invalid",
            _client_info=client_info,
            spec=["_http", "_base_url", "_client_info"],
        )

        # Make request.
        ds_api = self._make_one(client)
        response = ds_api.begin_transaction(project)

        # Check the result and verify the callers.
        self.assertEqual(response, rsp_pb)

        uri = _build_expected_url(client._base_url, project, "beginTransaction")
        request = _verify_protobuf_call(
            http, uri, datastore_pb2.BeginTransactionRequest()
        )
        # The RPC-over-HTTP request does not set the project in the request.
        self.assertEqual(request.project_id, u"")
Beispiel #3
0
    def test_it(self):
        from google.cloud.datastore_v1.proto import datastore_pb2

        http = object()
        project = "projectOK"
        method = "beginTransaction"
        base_url = "test.invalid"
        client_info = _make_client_info()
        request_pb = datastore_pb2.BeginTransactionRequest(project_id=project)

        response_pb = datastore_pb2.BeginTransactionResponse(transaction=b"7830rmc")
        patch = mock.patch(
            "google.cloud.datastore._http._request",
            return_value=response_pb.SerializeToString(),
        )
        with patch as mock_request:
            result = self._call_fut(
                http,
                project,
                method,
                base_url,
                client_info,
                request_pb,
                datastore_pb2.BeginTransactionResponse,
            )
            self.assertEqual(result, response_pb)

            mock_request.assert_called_once_with(
                http,
                project,
                method,
                request_pb.SerializeToString(),
                base_url,
                client_info,
            )
    def begin_transaction(self,
                          project_id,
                          transaction_options=None,
                          retry=google.api_core.gapic_v1.method.DEFAULT,
                          timeout=google.api_core.gapic_v1.method.DEFAULT,
                          metadata=None):
        """
        Begins a new transaction.

        Example:
            >>> from google.cloud import datastore_v1
            >>>
            >>> client = datastore_v1.DatastoreClient()
            >>>
            >>> project_id = ''
            >>>
            >>> response = client.begin_transaction(project_id)

        Args:
            project_id (str): The ID of the project against which to make the request.
            transaction_options (Union[dict, ~google.cloud.datastore_v1.types.TransactionOptions]): Options for a new transaction.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.datastore_v1.types.TransactionOptions`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.datastore_v1.types.BeginTransactionResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        request = datastore_pb2.BeginTransactionRequest(
            project_id=project_id,
            transaction_options=transaction_options,
        )
        return self._begin_transaction(
            request, retry=retry, timeout=timeout, metadata=metadata)
Beispiel #5
0
    def begin_transaction(self, project):
        """Perform a ``beginTransaction`` request.

        :type project: str
        :param project: The project to connect to. This is
                        usually your project name in the cloud console.

        :rtype: :class:`.datastore_pb2.BeginTransactionResponse`
        :returns: The returned protobuf response object.
        """
        request_pb = _datastore_pb2.BeginTransactionRequest()
        return _rpc(self.client._http, project, 'beginTransaction',
                    self.client._base_url, request_pb,
                    _datastore_pb2.BeginTransactionResponse)
Beispiel #6
0
    def begin_transaction(self, project_id, transaction_options=None):
        """Perform a ``beginTransaction`` request.

        :type project_id: str
        :param project_id: The project to connect to. This is
                           usually your project name in the cloud console.

        :type transaction_options: ~.datastore_v1.types.TransactionOptions
        :param transaction_options: (Optional) Options for a new transaction.

        :rtype: :class:`.datastore_pb2.BeginTransactionResponse`
        :returns: The returned protobuf response object.
        """
        request_pb = _datastore_pb2.BeginTransactionRequest()
        return _rpc(self.client._http, project_id, 'beginTransaction',
                    self.client._base_url, request_pb,
                    _datastore_pb2.BeginTransactionResponse)
Beispiel #7
0
    def test_begin_transaction(self):
        # Setup Expected Response
        transaction = b'-34'
        expected_response = {'transaction': transaction}
        expected_response = datastore_pb2.BeginTransactionResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = datastore_v1.DatastoreClient(channel=channel)

        # Setup Request
        project_id = 'projectId-1969970175'

        response = client.begin_transaction(project_id)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = datastore_pb2.BeginTransactionRequest(
            project_id=project_id)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Beispiel #8
0
    def test_it(self):
        from google.cloud.datastore_v1.proto import datastore_pb2

        http = object()
        project = 'projectOK'
        method = 'beginTransaction'
        base_url = 'test.invalid'
        request_pb = datastore_pb2.BeginTransactionRequest(
            project_id=project)

        response_pb = datastore_pb2.BeginTransactionResponse(
            transaction=b'7830rmc')
        patch = mock.patch('google.cloud.datastore._http._request',
                           return_value=response_pb.SerializeToString())
        with patch as mock_request:
            result = self._call_fut(
                http, project, method, base_url,
                request_pb, datastore_pb2.BeginTransactionResponse)
            self.assertEqual(result, response_pb)

            mock_request.assert_called_once_with(
                http, project, method, request_pb.SerializeToString(),
                base_url)
    def begin_transaction(
        self,
        project_id,
        transaction_options=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Begins a new transaction.

        Example:
            >>> from google.cloud import datastore_v1
            >>>
            >>> client = datastore_v1.DatastoreClient()
            >>>
            >>> # TODO: Initialize `project_id`:
            >>> project_id = ''
            >>>
            >>> response = client.begin_transaction(project_id)

        Args:
            project_id (str): The ID of the project against which to make the request.
            transaction_options (Union[dict, ~google.cloud.datastore_v1.types.TransactionOptions]): Options for a new transaction.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.datastore_v1.types.TransactionOptions`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.datastore_v1.types.BeginTransactionResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if "begin_transaction" not in self._inner_api_calls:
            self._inner_api_calls[
                "begin_transaction"
            ] = google.api_core.gapic_v1.method.wrap_method(
                self.transport.begin_transaction,
                default_retry=self._method_configs["BeginTransaction"].retry,
                default_timeout=self._method_configs["BeginTransaction"].timeout,
                client_info=self._client_info,
            )

        request = datastore_pb2.BeginTransactionRequest(
            project_id=project_id, transaction_options=transaction_options
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [("project_id", project_id)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header
            )
            metadata.append(routing_metadata)

        return self._inner_api_calls["begin_transaction"](
            request, retry=retry, timeout=timeout, metadata=metadata
        )