Datastore Example 1

Datastore Example showing setup

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Go

To learn how to install and use the client library for Datastore mode, see Datastore mode client libraries. For more information, see the Datastore mode Go API reference documentation.

To authenticate to Datastore mode, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

func TestWithdrawLowBal(t *testing.T) {
	ctx, done, err := aetest.NewContext()
	if err != nil {
		t.Fatal(err)
	}
	defer done()
	key := datastore.NewKey(ctx, "BankAccount", "", 1, nil)
	if _, err := datastore.Put(ctx, key, &BankAccount{100}); err != nil {
		t.Fatal(err)
	}

	err = withdraw(ctx, "myid", 128, 0)
	if err == nil || err.Error() != "insufficient funds" {
		t.Errorf("Error: %v; want insufficient funds error", err)
	}

	b := BankAccount{}
	if err := datastore.Get(ctx, key, &b); err != nil {
		t.Fatal(err)
	}
	if bal, want := b.Balance, 100; bal != want {
		t.Errorf("Balance %d, want %d", bal, want)
	}
}

Python

To learn how to install and use the client library for Datastore mode, see Datastore mode client libraries. For more information, see the Datastore mode Python API reference documentation.

To authenticate to Datastore mode, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

class TestModel(ndb.Model):
    """A model class used for testing."""

    number = ndb.IntegerProperty(default=42)
    text = ndb.StringProperty()


class TestEntityGroupRoot(ndb.Model):
    """Entity group root"""

    pass


def GetEntityViaMemcache(entity_key):
    """Get entity from memcache if available, from datastore if not."""
    entity = memcache.get(entity_key)
    if entity is not None:
        return entity
    key = ndb.Key(urlsafe=entity_key)
    entity = key.get()
    if entity is not None:
        memcache.set(entity_key, entity)
    return entity

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.