Hello World em Python

Este exemplo é um aplicativo "Hello World" simples, escrito em Python, que ilustra como:

  • Configure a autenticação.
  • Conecte a uma instância do Bigtable.
  • criar uma nova tabela;
  • Gravação de dados na tabela
  • Leitura dos dados
  • Exclusão da tabela

A biblioteca de cliente do Python para o Bigtable oferece duas APIs: asyncio e uma API síncrona. Se o aplicativo for assíncrono, use asyncio.

Configurar a autenticação

Para usar os exemplos de Python nesta página em um ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e configure o Application Default Credentials com suas credenciais de usuário.

  1. Instale a CLI do Google Cloud.

  2. Configure a CLI gcloud para usar sua identidade federada.

    Para mais informações, consulte Fazer login na CLI gcloud com sua identidade federada.

  3. Crie credenciais de autenticação local para sua conta de usuário:

    gcloud auth application-default login

    Se um erro de autenticação for retornado, confirme se você fez login na CLI gcloud com sua identidade federada.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Executar a amostra

Este exemplo usa o pacote do Bigtable das bibliotecas de cliente do Cloud para Python para se comunicar com o Bigtable.

Para executar este programa de amostra, siga as instruções do exemplo no GitHub.

Usar as bibliotecas de cliente do Cloud com o Bigtable

O aplicativo de amostra se conecta ao Bigtable e demonstra algumas operações.

Instalar e importar a biblioteca de cliente

Use o PIP para instalar os pacotes em Python, necessários em um ambiente virtualenv. A amostra inclui um arquivo de requisitos que define os pacotes necessários.

google-cloud-bigtable>=2.35.0

Importe os módulos.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters

Conectar ao Bigtable

Conecte-se ao Bigtable usando um bigtable.Client.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

client = bigtable.data.BigtableDataClientAsync(project=project_id)
table = client.get_table(instance_id, table_id)

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

client = bigtable.data.BigtableDataClient(project=project_id)
table = client.get_table(instance_id, table_id)

Criar uma tabela

Instancie um objeto de tabela usando Instance.table(). Crie um grupo de colunas e defina a política de coleta de lixo dele. Em seguida, passe o grupo de colunas para Table.create() a fim de criar a tabela.

from google.api_core.exceptions import AlreadyExists

from google.cloud import bigtable_admin_v2

# the data client only supports the data API. Table creation is an admin operation
# use admin client to create the table
print("Creating the {} table.".format(table_id))
admin_client = bigtable_admin_v2.BigtableTableAdminClient()
instance_path = admin_client.instance_path(project_id, instance_id)

print("Creating column family cf1 with Max Version GC rule...")
# Create a column family with GC policy : most recent N versions
# Define the GC policy to retain only the most recent 2 versions
max_versions_rule = bigtable_admin_v2.GcRule(max_num_versions=2)
column_family_id = "cf1"
column_families = {
    column_family_id: bigtable_admin_v2.ColumnFamily(gc_rule=max_versions_rule)
}
try:
    admin_client.create_table(
        parent=instance_path,
        table_id=table_id,
        table=bigtable_admin_v2.Table(column_families=column_families),
    )
except AlreadyExists:
    print("Table {} already exists.".format(table_id))

Gravar linhas em uma tabela

Execute um loop em uma lista de strings de saudação para criar algumas linhas novas na tabela. Em cada iteração, use Table.row() para definir uma linha e atribuir a ela uma chave de linha. Chame Row.set_cell() para definir o valor da célula atual e anexe a nova linha a uma matriz. Por fim, chame Table.mutate_rows() para adicionar as linhas à tabela.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Writing some greetings to the table.")
greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
mutations = []
column = b"greeting"
for i, value in enumerate(greetings):
    # Note: This example uses sequential numeric IDs for simplicity,
    # but this can result in poor performance in a production
    # application.  Since rows are stored in sorted order by key,
    # sequential keys can result in poor distribution of operations
    # across nodes.
    #
    # We recommend that you use bytestrings directly for row keys
    # where possible, rather than encoding strings.
    #
    # For more information about how to design a Bigtable schema for
    # the best performance, see the documentation:
    #
    #     https://cloud.google.com/bigtable/docs/schema-design
    row_key = f"greeting{i}".encode()
    row_mutation = bigtable.data.RowMutationEntry(
        row_key, bigtable.data.SetCell(column_family_id, column, value)
    )
    mutations.append(row_mutation)
await table.bulk_mutate_rows(mutations)

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Writing some greetings to the table.")
greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
mutations = []
column = b"greeting"
for i, value in enumerate(greetings):
    # Note: This example uses sequential numeric IDs for simplicity,
    # but this can result in poor performance in a production
    # application.  Since rows are stored in sorted order by key,
    # sequential keys can result in poor distribution of operations
    # across nodes.
    #
    # We recommend that you use bytestrings directly for row keys
    # where possible, rather than encoding strings.
    #
    # For more information about how to design a Bigtable schema for
    # the best performance, see the documentation:
    #
    #     https://cloud.google.com/bigtable/docs/schema-design
    row_key = f"greeting{i}".encode()
    row_mutation = bigtable.data.RowMutationEntry(
        row_key, bigtable.data.SetCell(column_family_id, column, value)
    )
    mutations.append(row_mutation)
table.bulk_mutate_rows(mutations)

Criar um filtro

Antes de ler os dados gravados, crie um filtro usando row_filters.CellsColumnLimitFilter() para limitar os dados retornados pelo Bigtable. Com esse filtro, o Bigtable retornará apenas a célula mais recente em cada coluna, mesmo que a tabela contenha células mais antigas que ainda não foram removidas durante a coleta de lixo.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

# Create a filter to only retrieve the most recent version of the cell
# for each column across entire row.
row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

Ler uma linha pela chave de linha

Chame o método Table.read_row() da tabela para receber uma referência da linha com uma chave de linha específica, transmitindo-a chave e o filtro, a fim de receber uma versão de cada valor naquela linha.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Getting a single greeting by row key.")
key = "greeting0".encode()

row = await table.read_row(key, row_filter=row_filter)
cell = row.cells[0]
print(cell.value.decode("utf-8"))

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Getting a single greeting by row key.")
key = "greeting0".encode()

row = table.read_row(key, row_filter=row_filter)
cell = row.cells[0]
print(cell.value.decode("utf-8"))

Verificar todas as linhas da tabela

Use Table.read_rows() para ler um intervalo de linhas de uma tabela.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Scanning for all greetings:")
query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
async for row in await table.read_rows_stream(query):
    cell = row.cells[0]
    print(cell.value.decode("utf-8"))

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.

print("Scanning for all greetings:")
query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
for row in table.read_rows_stream(query):
    cell = row.cells[0]
    print(cell.value.decode("utf-8"))

Excluir uma tabela

Exclua uma tabela com Table.delete().

from google.cloud import bigtable_admin_v2

# the data client only supports the data API. Table deletion is an admin operation
# use admin client to delete the table
admin_client = bigtable_admin_v2.BigtableTableAdminClient()
table_path = admin_client.table_path(project_id, instance_id, table_id)

print("Deleting the {} table.".format(table_id))
admin_client.delete_table(name=table_path)
table.close()
client.close()

Funcionamento em conjunto

Aqui está o exemplo completo sem comentários.

Asyncio

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar os exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations with the async APIs

Prerequisites:

- Create a Cloud Bigtable instance.
  https://cloud.google.com/bigtable/docs/creating-instance
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse
import asyncio

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters


row_filters


async def main(project_id, instance_id, table_id):
    client = bigtable.data.BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    from google.api_core.exceptions import AlreadyExists

    from google.cloud import bigtable_admin_v2

    print("Creating the {} table.".format(table_id))
    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = bigtable_admin_v2.GcRule(max_num_versions=2)
    column_family_id = "cf1"
    column_families = {
        column_family_id: bigtable_admin_v2.ColumnFamily(gc_rule=max_versions_rule)
    }
    async with bigtable_admin_v2.BigtableTableAdminAsyncClient() as admin_client:
        instance_path = admin_client.instance_path(project_id, instance_id)
        try:
            await admin_client.create_table(
                parent=instance_path,
                table_id=table_id,
                table=bigtable_admin_v2.Table(column_families=column_families),
            )
        except AlreadyExists:
            print("Table {} already exists.".format(table_id))

    try:
        from google.api_core.exceptions import FailedPrecondition, NotFound

        await table.read_row(
            b"greeting0",
            operation_timeout=120,
            retryable_errors=(
                *table.default_read_rows_retryable_errors,
                FailedPrecondition,
                NotFound,
            ),
        )
        print("Writing some greetings to the table.")
        greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
        mutations = []
        column = b"greeting"
        for i, value in enumerate(greetings):
            row_key = f"greeting{i}".encode()
            row_mutation = bigtable.data.RowMutationEntry(
                row_key, bigtable.data.SetCell(column_family_id, column, value)
            )
            mutations.append(row_mutation)
        await table.bulk_mutate_rows(mutations)

        row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

        print("Getting a single greeting by row key.")
        key = "greeting0".encode()

        row = await table.read_row(key, row_filter=row_filter)
        cell = row.cells[0]
        print(cell.value.decode("utf-8"))

        print("Scanning for all greetings:")
        query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
        async for row in await table.read_rows_stream(query):
            cell = row.cells[0]
            print(cell.value.decode("utf-8"))
    finally:
        from google.cloud import bigtable_admin_v2

        async with bigtable_admin_v2.BigtableTableAdminAsyncClient() as admin_client:
            table_path = admin_client.table_path(project_id, instance_id, table_id)

            print("Deleting the {} table.".format(table_id))
            await admin_client.delete_table(name=table_path)
        await table.close()
        await client.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("project_id", help="Your Cloud Platform project ID.")
    parser.add_argument(
        "instance_id", help="ID of the Cloud Bigtable instance to connect to."
    )
    parser.add_argument(
        "--table", help="Table to create and destroy.", default="Hello-Bigtable"
    )

    args = parser.parse_args()
    asyncio.run(main(args.project_id, args.instance_id, args.table))

Sincronizar

Para saber como instalar e usar a biblioteca de cliente do Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, acesse Configurar a autenticação para bibliotecas de cliente.

Antes de executar exemplos de código, defina a variável de ambiente GOOGLE_CLOUD_UNIVERSE_DOMAIN como s3nsapis.fr.



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations with the sync data APIs

Prerequisites:

- Create a Cloud Bigtable instance.
  https://cloud.google.com/bigtable/docs/creating-instance
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters


row_filters


def main(project_id, instance_id, table_id):
    client = bigtable.data.BigtableDataClient(project=project_id)
    table = client.get_table(instance_id, table_id)

    from google.api_core.exceptions import AlreadyExists

    from google.cloud import bigtable_admin_v2

    print("Creating the {} table.".format(table_id))
    admin_client = bigtable_admin_v2.BigtableTableAdminClient()
    instance_path = admin_client.instance_path(project_id, instance_id)

    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = bigtable_admin_v2.GcRule(max_num_versions=2)
    column_family_id = "cf1"
    column_families = {
        column_family_id: bigtable_admin_v2.ColumnFamily(gc_rule=max_versions_rule)
    }
    try:
        admin_client.create_table(
            parent=instance_path,
            table_id=table_id,
            table=bigtable_admin_v2.Table(column_families=column_families),
        )
    except AlreadyExists:
        print("Table {} already exists.".format(table_id))

    try:
        from google.api_core.exceptions import FailedPrecondition, NotFound

        table.read_row(
            b"greeting0",
            operation_timeout=120,
            retryable_errors=(
                *table.default_read_rows_retryable_errors,
                FailedPrecondition,
                NotFound,
            ),
        )
        print("Writing some greetings to the table.")
        greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
        mutations = []
        column = b"greeting"
        for i, value in enumerate(greetings):
            row_key = f"greeting{i}".encode()
            row_mutation = bigtable.data.RowMutationEntry(
                row_key, bigtable.data.SetCell(column_family_id, column, value)
            )
            mutations.append(row_mutation)
        table.bulk_mutate_rows(mutations)

        row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

        print("Getting a single greeting by row key.")
        key = "greeting0".encode()

        row = table.read_row(key, row_filter=row_filter)
        cell = row.cells[0]
        print(cell.value.decode("utf-8"))

        print("Scanning for all greetings:")
        query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
        for row in table.read_rows_stream(query):
            cell = row.cells[0]
            print(cell.value.decode("utf-8"))
    finally:
        from google.cloud import bigtable_admin_v2

        admin_client = bigtable_admin_v2.BigtableTableAdminClient()
        table_path = admin_client.table_path(project_id, instance_id, table_id)

        print("Deleting the {} table.".format(table_id))
        admin_client.delete_table(name=table_path)
        table.close()
        client.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("project_id", help="Your Cloud Platform project ID.")
    parser.add_argument(
        "instance_id", help="ID of the Cloud Bigtable instance to connect to."
    )
    parser.add_argument(
        "--table", help="Table to create and destroy.", default="Hello-Bigtable"
    )

    args = parser.parse_args()
    main(args.project_id, args.instance_id, args.table)