Exemple de tâche de marquage de Datastore terminée
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Exemple de tâche marquée comme terminée dans Datastore
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page provides code samples demonstrating how to mark a task as "done" within Google Cloud Datastore mode across multiple programming languages.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples utilize transactions to ensure data consistency when updating the task's status, setting the "done" field to true.\u003c/p\u003e\n"],["\u003cp\u003eEach code example includes instructions on setting up the Datastore client library and authenticating with Application Default Credentials for the specific language.\u003c/p\u003e\n"],["\u003cp\u003eThe samples cover various languages including C#, Go, Java, Node.js, PHP, Python, and Ruby, showcasing language-specific implementations of the task-completion process.\u003c/p\u003e\n"],["\u003cp\u003eThe page directs users to further documentation on getting started with the Firestore in Datastore mode API and the Datastore mode client libraries for more detailed information.\u003c/p\u003e\n"]]],[],null,["Example datastore mark task done\n\nExplore further\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Getting started with the Firestore in Datastore mode API](/datastore/docs/datastore-api-tutorial)\n\nCode sample \n\nC#\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode C# API\nreference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Datastore.V1/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /// \u003csummary\u003e\n /// Marks a task entity as done.\n /// \u003c/summary\u003e\n /// \u003cparam name=\"id\"\u003eThe ID of the task entity as given by Key.\u003c/param\u003e\n /// \u003creturns\u003etrue if the task was found.\u003c/returns\u003e\n bool MarkDone(long id)\n {\n using (var transaction = _db.BeginTransaction())\n {\n Entity task = transaction.Lookup(_keyFactory.CreateKey(id));\n if (task != null)\n {\n task[\"done\"] = true;\n transaction.Update(task);\n }\n transaction.Commit();\n return task != null;\n }\n }\n\nGo\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Go API\nreference documentation](https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"log\"\n\n \t\"cloud.google.com/go/datastore\"\n )\n\n // MarkDone marks the task done with the given ID.\n func MarkDone(projectID string, taskID int64) error {\n \tctx := context.Background()\n \tclient, err := datastore.https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest/index.html#cloud_google_com_go_datastore_Client_NewClient(ctx, projectID)\n \tif err != nil {\n \t\tlog.Fatalf(\"Could not create datastore client: %v\", err)\n \t}\n \tdefer client.Close()\n \t// Create a key using the given integer ID.\n \tkey := datastore.https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest/index.html#cloud_google_com_go_datastore_Key_IDKey(\"Task\", taskID, nil)\n\n \t// In a transaction load each task, set done to true and store.\n \t_, err = client.https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest/index.html#cloud_google_com_go_datastore_Client_RunInTransaction(ctx, func(tx *datastore.Transaction) error {\n \t\tvar task Task\n \t\tif err := tx.Get(key, &task); err != nil {\n \t\t\treturn err\n \t\t}\n \t\ttask.Done = true\n \t\t_, err := tx.Put(key, &task)\n \t\treturn err\n \t})\n \treturn err\n }\n\nJava\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Java API\nreference documentation](https://cloud.google.com/java/docs/reference/google-cloud-datastore/latest/history).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Marks a task entity as done.\n *\n * @param id The ID of the task entity as given by {@link Key#id()}\n * @return true if the task was found, false if not\n * @throws DatastoreException if the transaction fails\n */\n boolean markDone(long id) {\n Transaction transaction = datastore.newTransaction();\n try {\n Entity task = transaction.get(keyFactory.newKey(id));\n if (task != null) {\n transaction.put(Entity.newBuilder(task).set(\"done\", true).build());\n }\n transaction.commit();\n return task != null;\n } finally {\n if (transaction.isActive()) {\n transaction.rollback();\n }\n }\n }\n\nNode.js\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Node.js API\nreference documentation](https://cloud.google.com/nodejs/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n async function markDone(taskId) {\n const transaction = datastore.transaction();\n const taskKey = datastore.key(['Task', datastore.int(taskId)]);\n\n try {\n await transaction.run();\n const [task] = await transaction.get(taskKey);\n task.done = true;\n transaction.save({\n key: taskKey,\n data: task,\n });\n await transaction.commit();\n console.log(`Task ${taskId} updated successfully.`);\n } catch (err) {\n await transaction.rollback();\n }\n }\n\nPHP\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode PHP API\nreference documentation](https://googleapis.github.io/google-cloud-php/#/docs/cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\Datastore\\DatastoreClient;\n\n /**\n * Mark a task with a given id as done.\n *\n * @param string $projectId The Google Cloud project ID.\n * @param string $taskId\n */\n function mark_done(string $projectId, string $taskId)\n {\n $datastore = new DatastoreClient(['projectId' =\u003e $projectId]);\n\n $taskKey = $datastore-\u003ekey('Task', $taskId);\n $transaction = $datastore-\u003etransaction();\n $task = $transaction-\u003elookup($taskKey);\n $task['done'] = true;\n $transaction-\u003eupsert($task);\n $transaction-\u003ecommit();\n printf('Task %d updated successfully.' . PHP_EOL, $taskId);\n }\n\nPython\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Python API\nreference documentation](https://cloud.google.com/python/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from google.cloud import https://cloud.google.com/python/docs/reference/datastore/latest/\n\n def mark_done(client: https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html, task_id: str | int):\n with client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_transaction():\n # Create a key for an entity of kind \"Task\", and with the supplied\n # `task_id` as its Id\n key = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_key(\"Task\", task_id)\n # Use that key to load the entity\n task = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_get(key)\n\n if not task:\n raise ValueError(f\"Task {task_id} does not exist.\")\n\n # Update a field indicating that the associated\n # work has been completed\n task[\"done\"] = True\n\n # Persist the change back to Datastore\n client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_put(task)\n\nRuby\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Ruby API\nreference documentation](/ruby/docs/reference/google-cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def mark_done task_id\n require \"google/cloud/datastore\"\n\n datastore = Google::Cloud::https://cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore.html.https://cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore.html\n\n task = datastore.find \"Task\", task_id\n\n task[\"done\"] = true\n\n datastore.save task\n end\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=datastore)."]]