google-cloud-pubsub

Google Cloud Pub/Sub API client library

Apache-2.0 154 个版本 Python >=3.10
Google LLC <googleapis-packages@google.com>
安装
pip install google-cloud-pubsub
poetry add google-cloud-pubsub
pipenv install google-cloud-pubsub
conda install google-cloud-pubsub
描述

Python Client for Cloud Pub/Sub

|stable| |pypi| |versions|

Cloud Pub/Sub_: Provides reliable, many-to-many, asynchronous messaging between applications.

  • Client Library Documentation_
  • Product Documentation_

.. |stable| image:: https://img.shields.io/badge/support-stable-gold.svg :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels .. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-pubsub.svg :target: https://pypi.org/project/google-cloud-pubsub/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-pubsub.svg :target: https://pypi.org/project/google-cloud-pubsub/ .. _Cloud Pub/Sub: https://cloud.google.com/pubsub/docs .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/pubsub/latest/summary_overview .. _Product Documentation: https://cloud.google.com/pubsub/docs

Quick Start

In order to use this library, you first need to go through the following steps:

  1. Select or create a Cloud Platform project._
  2. Enable billing for your project._
  3. Enable the Cloud Pub/Sub._
  4. Set up Authentication._

.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project .. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project .. _Enable the Cloud Pub/Sub.: https://cloud.google.com/pubsub/docs .. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html

Installation


Install this library in a virtual environment using `venv`_. `venv`_ is a tool that
creates isolated Python environments. These isolated environments can have separate
versions of Python packages, which allows you to isolate one project's dependencies
from the dependencies of other projects.

With `venv`_, it's possible to install this library without needing system
install permissions, and without clashing with the installed system
dependencies.

.. _`venv`: https://docs.python.org/3/library/venv.html


Code samples and snippets

Code samples and snippets live in the samples/_ folder.

.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-pubsub/samples

Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ Our client libraries are compatible with all current active_ and maintenance_ versions of Python.

Python >= 3.10, including 3.14

.. _active: https://devguide.python.org/devcycle/#in-development-main-branch .. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches

Unsupported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Python <= 3.9

If you are using an end-of-life_ version of Python, we recommend that you update as soon as possible to an actively supported version.

.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches

Mac/Linux ^^^^^^^^^

.. code-block:: console

python3 -m venv <your-env>
source <your-env>/bin/activate
pip install google-cloud-pubsub

Windows ^^^^^^^

.. code-block:: console

py -m venv <your-env>
.\<your-env>\Scripts\activate
pip install google-cloud-pubsub

Example Usage


Publishing
^^^^^^^^^^

To publish data to Cloud Pub/Sub you must create a topic, and then publish
messages to it

.. code-block:: python

    import os
    from google.cloud import pubsub_v1

    publisher = pubsub_v1.PublisherClient()
    topic_name = 'projects/{project_id}/topics/{topic}'.format(
        project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
        topic='MY_TOPIC_NAME',  # Set this to something appropriate.
    )
    publisher.create_topic(name=topic_name)
    future = publisher.publish(topic_name, b'My first message!', spam='eggs')
    future.result()

To learn more, consult the `publishing documentation`_.

.. _publishing documentation: https://cloud.google.com/python/docs/reference/pubsub/latest/google.cloud.pubsub_v1.publisher.client.Client


Subscribing
^^^^^^^^^^^

To subscribe to data in Cloud Pub/Sub, you create a subscription based on
the topic, and subscribe to that, passing a callback function.

.. code-block:: python

    import os
    from google.cloud import pubsub_v1

    topic_name = 'projects/{project_id}/topics/{topic}'.format(
        project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
        topic='MY_TOPIC_NAME',  # Set this to something appropriate.
    )

    subscription_name = 'projects/{project_id}/subscriptions/{sub}'.format(
        project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
        sub='MY_SUBSCRIPTION_NAME',  # Set this to something appropriate.
    )

    def callback(message):
        print(message.data)
        message.ack()

    with pubsub_v1.SubscriberClient() as subscriber:
        subscriber.create_subscription(
            name=subscription_name, topic=topic_name)
        future = subscriber.subscribe(subscription_name, callback)

The future returned by the call to ``subscriber.subscribe`` can be used to
block the current thread until a given condition obtains:

.. code-block:: python

    try:
        future.result()
    except KeyboardInterrupt:
        future.cancel()

It is also possible to pull messages in a synchronous (blocking) fashion. To
learn more about subscribing, consult the `subscriber documentation`_.

.. _subscriber documentation: https://cloud.google.com/python/docs/reference/pubsub/latest/google.cloud.pubsub_v1.subscriber.client.Client


Authentication
^^^^^^^^^^^^^^

It is possible to specify the authentication method to use with the Pub/Sub
clients. This can be done by providing an explicit `Credentials`_ instance. Support
for various authentication methods is available from the `google-auth`_ library.

For example, to use JSON Web Tokens, provide a `google.auth.jwt.Credentials`_ instance:

.. code-block:: python

    import json
    from google.auth import jwt

    service_account_info = json.load(open("service-account-info.json"))
    audience = "https://pubsub.googleapis.com/google.pubsub.v1.Subscriber"

    credentials = jwt.Credentials.from_service_account_info(
        service_account_info, audience=audience
    )

    subscriber = pubsub_v1.SubscriberClient(credentials=credentials)

    # The same for the publisher, except that the "audience" claim needs to be adjusted
    publisher_audience = "https://pubsub.googleapis.com/google.pubsub.v1.Publisher"
    credentials_pub = credentials.with_claims(audience=publisher_audience)
    publisher = pubsub_v1.PublisherClient(credentials=credentials_pub)

.. _Credentials: https://google-auth.readthedocs.io/en/latest/reference/google.auth.credentials.html#google.auth.credentials.Credentials
.. _google-auth: https://google-auth.readthedocs.io/en/latest/index.html
.. _google.auth.jwt.Credentials: https://google-auth.readthedocs.io/en/latest/reference/google.auth.jwt.html#google.auth.jwt.Credentials


Versioning
----------

This library follows `Semantic Versioning`_.

It is currently in major version one (1.y.z), which means that the public API should be considered stable.

.. _Semantic Versioning: http://semver.org/

Contributing
------------

Contributions to this library are always welcome and highly encouraged.

See the `CONTRIBUTING doc`_ for more information on how to get started.

.. _CONTRIBUTING doc: https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst

Community
---------

The best place to ask questions is via Stackoverflow: https://stackoverflow.com/questions/tagged/google-cloud-pubsub


License
-------

Apache 2.0 - See `the LICENSE`_ for more information.

.. _the LICENSE: https://github.com/googleapis/google-cloud-python/blob/main/LICENSE

Next Steps
~~~~~~~~~~

-  Read the `Client Library Documentation`_ for Cloud Pub/Sub
   to see other available methods on the client.
-  Read the `Cloud Pub/Sub Product documentation`_ to learn
   more about the product and see How-to Guides.
-  View this `README`_ to see the full list of Cloud
   APIs that we cover.

.. _Cloud Pub/Sub Product documentation:  https://cloud.google.com/pubsub/docs
.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst

Logging
-------

This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes.
Note the following:

#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging.
#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**.
#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below.

Simple, environment-based configuration

To enable logging for this library without any changes in your code, set the :code:GOOGLE_SDK_PYTHON_LOGGING_SCOPE environment variable to a valid Google logging scope. This configures handling of logging events (at level :code:logging.DEBUG or higher) from this library in a default manner, emitting the logged messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging event.

A logging scope is a period-separated namespace that begins with :code:google, identifying the Python module or package to log.

  • Valid logging scopes: :code:google, :code:google.cloud.asset.v1, :code:google.api, :code:google.auth, etc.
  • Invalid logging scopes: :code:foo, :code:123, etc.

NOTE: If the logging scope is invalid, the library does not set up any logging handlers.

Environment-Based Examples ^^^^^^^^^^^^^^^^^^^^^^^^^^

  • Enabling the default handler for all Google-based loggers

.. code-block:: console

export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google
  • Enabling the default handler for a specific Google module (for a client library called :code:library_v1):

.. code-block:: console

export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1

Advanced, code-based configuration


You can also configure a valid logging scope using Python's standard `logging` mechanism.

Code-Based Examples
^^^^^^^^^^^^^^^^^^^

- Configuring a handler for all Google-based loggers

.. code-block:: python

    import logging
    
    from google.cloud import library_v1
    
    base_logger = logging.getLogger("google")
    base_logger.addHandler(logging.StreamHandler())
    base_logger.setLevel(logging.DEBUG)

- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`):

.. code-block:: python

    import logging
    
    from google.cloud import library_v1
    
    base_logger = logging.getLogger("google.cloud.library_v1")
    base_logger.addHandler(logging.StreamHandler())
    base_logger.setLevel(logging.DEBUG)

Logging details
~~~~~~~~~~~~~~~

#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root
   logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set
   :code:`logging.getLogger("google").propagate = True` in your code.
#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for
   one library, but decide you need to also set up environment-based logging configuration for another library.

   #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual
      if the code -based configuration gets applied first.

#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get
   executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured.
   (This is the reason for 2.i. above.)
版本列表
2.39.0 2026-06-03
2.38.0 2026-05-07
2.37.0 2026-04-10
2.36.0 2026-03-12
2.35.0 2026-02-05
2.34.0 2025-12-16
2.33.0 2025-10-30
2.32.0 2025-10-28
2.31.1 2025-07-28
2.31.0 2025-07-08
2.30.0 2025-06-10
2.29.1 2025-06-03
2.29.0 2025-03-20
2.28.0 2025-01-30
2.27.3 2025-01-24
2.27.2 2025-01-06
2.27.1 2024-11-13
2.27.0 2024-11-13
2.26.1 2024-10-15
2.26.0 2024-10-09
2.25.2 2024-09-30
2.25.1 2024-09-30
2.25.0 2024-09-29
2.23.1 2024-09-09
2.23.0 2024-07-29
2.22.0 2024-07-06
2.21.5 2024-06-20
2.21.4 2024-06-18
2.21.3 2024-06-10
2.21.2 2024-05-30
2.21.1 2024-04-04
2.21.0 2024-03-26
2.20.3 2024-03-21
2.20.2 2024-03-15
2.20.1 2024-03-06
2.20.0 2024-03-06
2.19.8 2024-03-05
2.19.7 2024-02-26
2.19.6 2024-02-23
2.19.5 2024-02-23
2.19.4 2024-02-09
2.19.3 2024-02-09
2.19.2 2024-02-08
2.19.1 2024-02-02
2.19.0 2023-12-11
2.18.4 2023-09-10
2.18.3 2023-08-18
2.18.2 2023-08-07
2.18.1 2023-07-27
2.18.0 2023-07-12
2.17.1 2023-05-23
2.17.0 2023-05-12
2.16.1 2023-05-06
2.16.0 2023-04-06
2.15.2 2023-03-23
2.15.1 2023-03-15
2.15.0 2023-02-23
2.14.1 2023-02-08
2.14.0 2023-01-19
2.13.12 2023-01-10
2.13.11 2022-11-11
2.13.10 2022-10-14
2.13.9 2022-10-10
2.13.8 2022-10-14
2.13.7 2022-09-22
2.13.6 2022-08-12
2.13.5 2022-08-10
2.13.4 2022-07-16
2.13.3 2022-07-13
2.13.2 2022-07-11
2.13.1 2022-07-07
2.13.0 2022-06-07
2.12.1 2022-05-11
2.12.0 2022-04-06
2.11.1 2022-06-09
2.11.0 2022-03-09
2.10.0 2022-03-04
2.9.0 2021-11-10
2.8.0 2021-09-06
2.7.1 2021-08-19
2.7.0 2021-07-28
2.6.1 2021-07-12
2.6.0 2021-06-21
2.5.0 2021-05-18
2.4.2 2021-05-10
2.4.1 2021-03-31
2.4.0 2021-02-22
2.3.0 2021-02-08
2.2.0 2020-12-04
2.1.0 2020-09-21
2.0.0 2020-09-14
1.7.2 2022-06-09
1.7.1 2022-04-06
1.7.0 2020-07-13
1.6.1 2020-07-06
1.6.0 2020-06-09
1.5.0 2020-05-12
1.4.3 2020-04-16
1.4.2 2020-03-26
1.4.1 2020-03-23
1.4.0 2020-03-23
1.3.1 2020-02-28
1.3.0 2020-02-20
1.2.0 2020-02-05
1.1.0 2019-12-11
1.0.2 2019-09-30
1.0.1 2019-09-27
1.0.0 2019-08-29
0.45.0 2019-07-31
0.44.0 2019-07-29
0.43.0 2019-07-30
0.42.1 2019-06-18
0.42.0 2019-06-18
0.41.0 2019-05-15
0.40.0 2019-03-15
0.39.1 2018-12-18
0.39.0 2018-11-27
0.38.0 2018-09-12
0.37.2 2018-08-21
0.37.1 2018-08-16
0.37.0 2018-08-14
0.36.0 2018-08-10
0.35.4 2018-06-06
0.35.3 2018-06-05
0.35.2 2018-05-30
0.35.1 2018-05-29
0.35.0 2018-05-23
0.34.0 2018-04-27
0.33.1 2018-04-03
0.33.0 2018-03-20
0.32.1 2018-03-07
0.32.0 2018-02-23
0.31.0 2018-02-20
0.30.1 2017-12-21
0.30.0 2017-12-19
0.29.4 2017-12-11
0.29.3 2017-12-08
0.29.2 2017-11-30
0.29.1 2017-11-27
0.29.0 2017-10-31
0.28.4 2017-10-13
0.28.3 2017-09-05
0.28.2 2017-08-25
0.28.1 2017-08-24
0.28.0 2017-08-24
0.27.0 2017-08-05
0.26.0 2017-06-26
0.25.0 2017-04-28
0.24.0 2017-03-31
0.23.0 2017-02-25
0.22.0 2016-12-10
0.21.0 2016-11-14
0.20.0 2016-09-29