הוספת משימה

יצירה ושמירה של ישות מהסוג ההיפותטי Task

המשך למידה

לקבלת הסבר מפורט שכולל את דוגמת הקוד הזו, קראו את המאמר:

דוגמת קוד

C#

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode C# API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/// <summary>
///  Adds a task entity to the Datastore
/// </summary>
/// <param name="description">The task description.</param>
/// <returns>The key of the entity.</returns>
Key AddTask(string description)
{
    Entity task = new Entity()
    {
        Key = _keyFactory.CreateIncompleteKey(),
        ["description"] = new Value()
        {
            StringValue = description,
            ExcludeFromIndexes = true
        },
        ["created"] = DateTime.UtcNow,
        ["done"] = false
    };
    return _db.Insert(task);
}

Go

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode Go API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"log"
	"time"

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

// Task is the model used to store tasks in the datastore.
type Task struct {
	Desc    string    `datastore:"description"`
	Created time.Time `datastore:"created"`
	Done    bool      `datastore:"done"`
	id      int64     // The integer ID used in the datastore.
}

// AddTask adds a task with the given description to the datastore,
// returning the key of the newly created entity.
func AddTask(projectID string, desc string) (*datastore.Key, 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()
	task := &Task{
		Desc:    desc,
		Created: time.Now(),
	}
	key := datastore.IncompleteKey("Task", nil)
	return client.Put(ctx, key, task)

}

Java

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode Java API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Adds a task entity to the Datastore.
 *
 * @param description The task description
 * @return The {@link Key} of the entity
 * @throws DatastoreException if the ID allocation or put fails
 */
Key addTask(String description) {
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity task =
      Entity.newBuilder(key)
          .set(
              "description",
              StringValue.newBuilder(description).setExcludeFromIndexes(true).build())
          .set("created", Timestamp.now())
          .set("done", false)
          .build();
  datastore.put(task);
  return key;
}

PHP

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode PHP API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Create a new task with a given description.
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $description
 */
function add_task(string $projectId, string $description)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $taskKey = $datastore->key('Task');
    $task = $datastore->entity(
        $taskKey,
        [
            'created' => new DateTime(),
            'description' => $description,
            'done' => false
        ],
        ['excludeFromIndexes' => ['description']]
    );
    $datastore->insert($task);
    printf('Created new task with ID %d.' . PHP_EOL, $task->key()->pathEnd()['id']);
}

Python

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode Python API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import datastore

def add_task(client: datastore.Client, description: str):
    # Create an incomplete key for an entity of kind "Task". An incomplete
    # key is one where Datastore will automatically generate an Id
    key = client.key("Task")

    # Create an unsaved Entity object, and tell Datastore not to index the
    # `description` field
    task = datastore.Entity(key, exclude_from_indexes=("description",))

    # Apply new field values and save the Task entity to Datastore
    task.update(
        {
            "created": datetime.datetime.now(tz=datetime.timezone.utc),
            "description": description,
            "done": False,
        }
    )
    client.put(task)
    return task.key

Ruby

מידע על התקנת ספריית הלקוח למצב Datastore ושימוש בה מופיע במאמר ספריות הלקוח של מצב Datastore. מידע נוסף מופיע במאמרי העזרה של Datastore mode Ruby API.

כדי לבצע אימות במצב Datastore, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def add_task description
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  task = datastore.entity "Task" do |t|
    t["description"] = description
    t["created"]     = Time.now
    t["done"]        = false
    t.exclude_from_indexes! "description", true
  end

  datastore.save task

  puts task.key.id

  task.key.id
end

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , אפשר להיעזר בGoogle Cloud דפדפן לדוגמה.