数据存储区标记任务示例

数据存储区标记任务示例

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 C# API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/// <summary>
/// Marks a task entity as done.
/// </summary>
/// <param name="id">The ID of the task entity as given by Key.</param>
/// <returns>true if the task was found.</returns>
bool MarkDone(long id)
{
    using (var transaction = _db.BeginTransaction())
    {
        Entity task = transaction.Lookup(_keyFactory.CreateKey(id));
        if (task != null)
        {
            task["done"] = true;
            transaction.Update(task);
        }
        transaction.Commit();
        return task != null;
    }
}

Go

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Go API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"log"

	"cloud.google.com/go/datastore"
)

// MarkDone marks the task done with the given ID.
func MarkDone(projectID string, taskID int64) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}
	defer client.Close()
	// Create a key using the given integer ID.
	key := datastore.IDKey("Task", taskID, nil)

	// In a transaction load each task, set done to true and store.
	_, err = client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
		var task Task
		if err := tx.Get(key, &task); err != nil {
			return err
		}
		task.Done = true
		_, err := tx.Put(key, &task)
		return err
	})
	return err
}

Java

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Java API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * Marks a task entity as done.
 *
 * @param id The ID of the task entity as given by {@link Key#id()}
 * @return true if the task was found, false if not
 * @throws DatastoreException if the transaction fails
 */
boolean markDone(long id) {
  Transaction transaction = datastore.newTransaction();
  try {
    Entity task = transaction.get(keyFactory.newKey(id));
    if (task != null) {
      transaction.put(Entity.newBuilder(task).set("done", true).build());
    }
    transaction.commit();
    return task != null;
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}

Node.js

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Node.js API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

async function markDone(taskId) {
  const transaction = datastore.transaction();
  const taskKey = datastore.key(['Task', datastore.int(taskId)]);

  try {
    await transaction.run();
    const [task] = await transaction.get(taskKey);
    task.done = true;
    transaction.save({
      key: taskKey,
      data: task,
    });
    await transaction.commit();
    console.log(`Task ${taskId} updated successfully.`);
  } catch (err) {
    await transaction.rollback();
  }
}

PHP

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 PHP API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Mark a task with a given id as done.
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $taskId
 */
function mark_done(string $projectId, string $taskId)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $taskKey = $datastore->key('Task', $taskId);
    $transaction = $datastore->transaction();
    $task = $transaction->lookup($taskKey);
    $task['done'] = true;
    $transaction->upsert($task);
    $transaction->commit();
    printf('Task %d updated successfully.' . PHP_EOL, $taskId);
}

Python

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Python API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import datastore

def mark_done(client: datastore.Client, task_id: str | int):
    with client.transaction():
        # Create a key for an entity of kind "Task", and with the supplied
        # `task_id` as its Id
        key = client.key("Task", task_id)
        # Use that key to load the entity
        task = client.get(key)

        if not task:
            raise ValueError(f"Task {task_id} does not exist.")

        # Update a field indicating that the associated
        # work has been completed
        task["done"] = True

        # Persist the change back to Datastore
        client.put(task)

Ruby

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Ruby API 参考文档

如需向 Datastore 模式进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

def mark_done task_id
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  task = datastore.find "Task", task_id

  task["done"] = true

  datastore.save task
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器