Python hello world

הדוגמה הזו היא אפליקציית hello world, שנכתבה ב-Python, שממחישה איך לבצע את הפעולות הבאות:

  • מגדירים אימות.
  • מתחברים למכונה של Bigtable.
  • ליצור טבלה חדשה.
  • כתיבת נתונים בטבלה.
  • קוראים את הנתונים בחזרה.
  • מוחקים את הטבלה.

ספריית הלקוח של Python ל-Bigtable מציעה שני ממשקי API, ‏ asyncio וממשק API סינכרוני. אם האפליקציה שלכם היא אסינכרונית, אתם צריכים להשתמש ב-asyncio.

מגדירים אימות

כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  3. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

מריצים את הדוגמה

בדוגמה הזו נעשה שימוש בחבילת Bigtable של ספריות הלקוח של Cloud לשימוש ב-Python כדי ליצור תקשורת עם Bigtable. חבילת Bigtable היא הבחירה הטובה ביותר לאפליקציות חדשות. אם אתם צריכים להעביר עומס עבודה קיים של HBase אל Bigtable, תוכלו לעיין בדוגמה 'hello world' שמשתמשת בחבילת HappyBase.

כדי להריץ את תוכנית הדוגמה הזו, פועלים לפי ההוראות לדוגמה ב-GitHub.

שימוש בספריות הלקוח של Cloud עם Bigtable

אפליקציית הדוגמה מתחברת ל-Bigtable ומדגימה כמה פעולות.

התקנה וייבוא של ספריית הלקוח

משתמשים ב-PIP כדי להתקין את חבילות Python הנדרשות בסביבת virtualenv. הדוגמה כוללת קובץ דרישות שמגדיר את החבילות הנדרשות.

google-cloud-bigtable==2.35.0
google-cloud-core==2.5.0

מייבאים את המודולים.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

from datetime import datetime, timezone

from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable import row_filters

התחברות ל-Bigtable

מתחברים ל-Bigtable באמצעות bigtable.Client.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

# The client must be created with admin=True because it will create a
# table.
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)

צור טבלה

יוצרים מופע של אובייקט טבלה באמצעות Instance.table(). יוצרים קבוצת עמודות ומגדירים את מנגנון איסוף הזבל שלה, ואז מעבירים את קבוצת העמודות אל Table.create() כדי ליצור את הטבלה.

print("Creating the {} table.".format(table_id))
table = instance.table(table_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.column_family.MaxVersionsGCRule(2)
column_family_id = b"cf1"
column_families = {column_family_id: max_versions_rule}
if not table.exists():
    table.create(column_families=column_families)
else:
    print("Table {} already exists.".format(table_id))

כתיבת שורות בטבלה

מבצעים לולאה ברשימה של מחרוזות ברכה כדי ליצור כמה שורות חדשות לטבלה. בכל איטרציה, משתמשים ב-Table.row() כדי להגדיר שורה ולהקצות לה מפתח שורה, קוראים ל-Row.set_cell() כדי להגדיר ערך לתא הנוכחי ומצרפים את השורה החדשה למערך של שורות. לבסוף, קוראים לפונקציה Table.mutate_rows() כדי להוסיף את השורות לטבלה.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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)

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

print("Writing some greetings to the table.")
greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
rows = []
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 = table.direct_row(row_key)
    row.set_cell(
        column_family_id, column, value, timestamp=datetime.now(timezone.utc),
    )
    rows.append(row)
table.mutate_rows(rows)

יצירת מסנן

לפני שקוראים את הנתונים שכתבתם, צריך ליצור מסנן באמצעות row_filters.CellsColumnLimitFilter() כדי להגביל את הנתונים שמוחזרים מ-Bigtable. מסנן זה מורה ל-Bigtable להחזיר רק את התא האחרון בכל עמודה, גם אם הטבלה מכילה תאים ישנים יותר שטרם הוסרו במהלך איסוף האשפה.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

# 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)

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

קריאת שורה לפי מפתח השורה

מפעילים את השיטה Table.read_row() של הטבלה כדי לקבל הפניה לשורה עם מפתח שורה ספציפי, מעבירים את המפתח ואת המסנן כדי לקבל גרסה אחת של כל ערך בשורה הזו.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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"))

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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

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

סריקת כל השורות בטבלה

כדי לקרוא טווח של שורות מטבלה, משתמשים ב-Table.read_rows().

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

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"))

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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

print("Scanning for all greetings:")
partial_rows = table.read_rows(filter_=row_filter)

for row in partial_rows:
    column_family_id_str = column_family_id.decode("utf-8")
    cell = row.cells[column_family_id_str][column][0]
    print(cell.value.decode("utf-8"))

מחיקת טבלה

מחיקת טבלה באמצעות Table.delete().

print("Deleting the {} table.".format(table_id))
table.delete()

סיכום של כל המידע

זוהי הדוגמה המלאה ללא הערות.

Asyncio

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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



"""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 ..utils import wait_for_table

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.cloud.bigtable import column_family

    print("Creating the {} table.".format(table_id))
    admin_client = bigtable.Client(project=project_id, admin=True)
    admin_instance = admin_client.instance(instance_id)
    admin_table = admin_instance.table(table_id)

    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = column_family.MaxVersionsGCRule(2)
    column_family_id = b"cf1"
    column_families = {column_family_id: max_versions_rule}
    if not admin_table.exists():
        admin_table.create(column_families=column_families)
    else:
        print("Table {} already exists.".format(table_id))

    try:
        wait_for_table(admin_table)
        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:
        print("Deleting the {} table.".format(table_id))
        admin_table.delete()


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))

סנכרון

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

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



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.

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 ..utils import wait_for_table

from datetime import datetime, timezone

from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable import row_filters


row_filters
column_family


def main(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)

    print("Creating the {} table.".format(table_id))
    table = instance.table(table_id)

    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = bigtable.column_family.MaxVersionsGCRule(2)
    column_family_id = b"cf1"
    column_families = {column_family_id: max_versions_rule}
    if not table.exists():
        table.create(column_families=column_families)
    else:
        print("Table {} already exists.".format(table_id))

    try:
        wait_for_table(table)

        print("Writing some greetings to the table.")
        greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
        rows = []
        column = b"greeting"
        for i, value in enumerate(greetings):
            row_key = f"greeting{i}".encode()
            row = table.direct_row(row_key)
            row.set_cell(
                column_family_id, column, value, timestamp=datetime.now(timezone.utc),
            )
            rows.append(row)
        table.mutate_rows(rows)

        row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

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

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

        print("Scanning for all greetings:")
        partial_rows = table.read_rows(filter_=row_filter)

        for row in partial_rows:
            column_family_id_str = column_family_id.decode("utf-8")
            cell = row.cells[column_family_id_str][column][0]
            print(cell.value.decode("utf-8"))

    finally:
        print("Deleting the {} table.".format(table_id))
        table.delete()


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)