跳转到主要内容

Google Cloud Spanner API客户端库

项目描述

GA pypi versions

Cloud Spanner是全球首个提供强一致性和水平扩展的完全管理的云数据库服务,适用于关键在线事务处理(OLTP)应用。使用Cloud Spanner,您可以享受关系型数据库的所有传统优势;但与任何其他关系型数据库服务不同,Cloud Spanner可以水平扩展到数百或数千个服务器,以处理最大的交易负载。

快速入门

为了使用此库,您首先需要完成以下步骤

  1. 选择或创建一个云平台项目。

  2. 为项目启用计费。

  3. 启用Google Cloud Spanner API。

  4. 设置身份验证。

安装

使用pip在virtualenv中安装此库。 virtualenv是一种创建隔离Python环境的工具。它解决的基本问题是依赖和版本问题,间接还有权限问题。

使用virtualenv,可以在不需要系统安装权限的情况下安装此库,并且不会与已安装的系统依赖冲突。

支持的Python版本

Python >= 3.7

已弃用的Python版本

Python == 2.7. Python == 3.5. Python == 3.6.

Mac/Linux

pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-spanner

Windows

pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-spanner

示例用法

在事务中执行任意SQL

通常,您将与Cloud Spanner一起使用事务。实现这一点的首选机制是创建一个单独的函数,该函数作为database.run_in_transaction的回调执行。

# First, define the function that represents a single "unit of work"
# that should be run within the transaction.
def update_anniversary(transaction, person_id, unix_timestamp):
    # The query itself is just a string.
    #
    # The use of @parameters is recommended rather than doing your
    # own string interpolation; this provides protections against
    # SQL injection attacks.
    query = """SELECT anniversary FROM people
        WHERE id = @person_id"""

    # When executing the SQL statement, the query and parameters are sent
    # as separate arguments. When using parameters, you must specify
    # both the parameters themselves and their types.
    row = transaction.execute_sql(
        query=query,
        params={'person_id': person_id},
        param_types={
            'person_id': types.INT64_PARAM_TYPE,
        },
    ).one()

    # Now perform an update on the data.
    old_anniversary = row[0]
    new_anniversary = _compute_anniversary(old_anniversary, years)
    transaction.update(
        'people',
        ['person_id', 'anniversary'],
        [person_id, new_anniversary],
    )

# Actually run the `update_anniversary` function in a transaction.
database.run_in_transaction(update_anniversary,
    person_id=42,
    unix_timestamp=1335020400,
)

使用事务选择记录

一旦您有了事务对象(例如发送给run_in_transaction的第一个参数),读取数据就变得容易了。

# Define a SELECT query.
query = """SELECT e.first_name, e.last_name, p.telephone
    FROM employees as e, phones as p
    WHERE p.employee_id == e.employee_id"""

# Execute the query and return results.
result = transaction.execute_sql(query)
for row in result.rows:
    print(row)

使用事务和数据操作语言(DML)插入记录

使用execute_update()方法执行DML语句。

spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)

def insert_singers(transaction):
    row_ct = transaction.execute_update(
        "INSERT Singers (SingerId, FirstName, LastName) "
        " VALUES (10, 'Virginia', 'Watson')"
    )

    print("{} record(s) inserted.".format(row_ct))

database.run_in_transaction(insert_singers)

使用事务使用突变插入记录

要将一个或多个记录添加到表中,请使用insert

transaction.insert(
    'citizens',
    columns=['email', 'first_name', 'last_name', 'age'],
    values=[
        ['phred@exammple.com', 'Phred', 'Phlyntstone', 32],
        ['bharney@example.com', 'Bharney', 'Rhubble', 31],
    ],
)

使用事务使用DML更新记录

spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)

def update_albums(transaction):
    row_ct = transaction.execute_update(
        "UPDATE Albums "
        "SET MarketingBudget = MarketingBudget * 2 "
        "WHERE SingerId = 1 and AlbumId = 1"
    )

    print("{} record(s) updated.".format(row_ct))

database.run_in_transaction(update_albums)

使用事务使用突变更新记录

Transaction.update更新表中的一个或多个现有记录。如果任何记录尚不存在,则失败。

transaction.update(
    'citizens',
    columns=['email', 'age'],
    values=[
        ['phred@exammple.com', 33],
        ['bharney@example.com', 32],
    ],
)

连接API

连接API是Python Spanner API的包装,遵循PEP-249编写,通过连接对象提供与Spanner数据库通信的简单方式。

from google.cloud.spanner_dbapi.connection import connect

connection = connect("instance-id", "database-id")
connection.autocommit = True

cursor = connection.cursor()
cursor.execute("SELECT * FROM table_name")

result = cursor.fetchall()

中止事务重试机制

!autocommit模式下,事务可以由于临时错误而中止。在大多数情况下,重试中止的事务可以解决问题。为了简化,连接跟踪当前事务中执行的SQL语句。如果事务中止,连接将启动一个新的连接并重新执行所有语句。在这个过程中,连接会检查重试的语句是否返回与原始语句相同的结果。如果结果不同,则放弃事务,因为底层数据已更改,自动重试无法进行。

仅在!autocommit模式下启用中止事务的自动重试,因为在autocommit模式下事务永远不会中止。

下一步

  • 有关如何使用此客户端库连接到Cloud Spanner的说明,请参阅客户端库文档

  • 阅读产品文档以了解有关产品的更多信息并查看教程。

项目详情


发布历史 发布通知 | RSS源

下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分发

google_cloud_spanner-3.49.1.tar.gz (558.5 kB 查看哈希值)

上传时间 源代码

构建分发

google_cloud_spanner-3.49.1-py2.py3-none-any.whl (402.7 kB 查看哈希值)

上传时间 Python 2 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面