### Run Quickstart Publisher Sample Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst Execute the quickstart publisher Python script. This sample demonstrates basic publishing functionality. ```bash python3 quickstart/pub.py ``` -------------------------------- ### Run Quickstart Subscriber Sample Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst Execute the quickstart subscriber Python script. This sample demonstrates basic subscription functionality. ```bash python3 quickstart/sub.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/install_deps.tmpl.rst Install all the required Python packages listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install google-cloud-pubsub with libcst extra Source: https://github.com/googleapis/python-pubsub/blob/main/docs/UPGRADING.md Install the library with the `libcst` extra to use the provided script for code conversion. ```bash python3 -m pip install google-cloud-pubsub[libcst] ``` -------------------------------- ### Install google-cloud-pubsub with virtualenv (Windows) Source: https://github.com/googleapis/python-pubsub/blob/main/README.rst Installs the google-cloud-pubsub library using pip within a virtual environment on Windows. ```console pip install virtualenv virtualenv \Scripts\activate \Scripts\pip.exe install google-cloud-pubsub ``` -------------------------------- ### Publisher client initialization and topic listing (Before v2.0.0) Source: https://github.com/googleapis/python-pubsub/blob/main/UPGRADING.md Example of initializing the Publisher client and listing topics using the older API signature. ```python from google.cloud import pubsub publisher = pubsub.PublisherClient() project_path = "projects/{}".format(PROJECT_ID) topics = publisher.list_topics(project_path) ``` -------------------------------- ### Instantiate a Subscriber Client Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/index.md Instantiate a Pub/Sub subscriber client using a context manager. Ensure the 'google-cloud-pubsub' library is installed. ```python from google.cloud import pubsub with pubsub.SubscriberClient() as subscriber: # ... ``` -------------------------------- ### Publisher client initialization and topic listing (After v2.0.0) Source: https://github.com/googleapis/python-pubsub/blob/main/UPGRADING.md Example of initializing the Publisher client and listing topics using the new API signature with a request object. ```python from google.cloud import pubsub publisher = pubsub.PublisherClient() project_path = f"projects/{PROJECT_ID}" topics = publisher.list_topics(request={"project": project_path}) ``` -------------------------------- ### Get Help for Pub/Sub Sample Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/README.tmpl.rst Display help information for a Python Pub/Sub sample script. This is useful for understanding command-line arguments and options. ```bash $ python sample.py --help ``` -------------------------------- ### Install PortAudio on Debian/Ubuntu Linux Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/install_portaudio.tmpl.rst Install the PortAudio development package on Debian or Ubuntu systems using apt-get. ```bash apt-get install portaudio19-dev python-all-dev ``` -------------------------------- ### Install Python Development Headers Source: https://github.com/googleapis/python-pubsub/blob/main/CONTRIBUTING.rst If you encounter 'Python.h' not found errors, install the 'python-dev' package using apt-get. ```bash $ sudo apt-get install python-dev ``` -------------------------------- ### Install google-cloud-pubsub with virtualenv (Mac/Linux) Source: https://github.com/googleapis/python-pubsub/blob/main/README.rst Installs the google-cloud-pubsub library using pip within a virtual environment on macOS or Linux. ```console pip install virtualenv virtualenv source /bin/activate /bin/pip install google-cloud-pubsub ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/googleapis/python-pubsub/blob/main/CONTRIBUTING.rst Enable pre-commit hooks to automate linting and formatting checks before each commit. ```bash $ pre-commit install pre-commit installed at .git/hooks/pre-commit ``` -------------------------------- ### Troubleshoot PyAudio installation on macOS Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/install_portaudio.tmpl.rst If pip install fails due to missing portaudio.h, use these flags to specify include and library paths. ```bash pip install --global-option='build_ext' --global-option='-I/usr/local/include' --global-option='-L/usr/local/lib' pyaudio ``` -------------------------------- ### Instantiate Publisher Client Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/index.md Create an instance of the PublisherClient to interact with Google Cloud Pub/Sub for publishing messages. No specific setup is required beyond importing the library. ```python from google.cloud import pubsub publish_client = pubsub.PublisherClient() ``` -------------------------------- ### Create a Pub/Sub Subscription Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/index.md Create a new subscription to an existing topic. Replace PROJECT, SUBSCRIPTION, and TOPIC with your specific values. This requires a PublisherClient to get the topic path. ```python # Substitute PROJECT, SUBSCRIPTION, and TOPIC with appropriate values for # your application. # from google.cloud import pubsub # publisher = pubsub.PublisherClient() topic_path = publisher.topic_path(PROJECT, TOPIC) with pubsub.SubscriberClient() as subscriber: sub_path = subscriber.subscription_path(PROJECT, SUBSCRIPTION) subscriber.create_subscription(request={"name": sub_path, "topic": topic_path}) ``` -------------------------------- ### IAM Policy YAML Structure Example Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md An example of an Identity and Access Management (IAM) policy structure in YAML format, illustrating role bindings and conditional access. ```yaml bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') ``` -------------------------------- ### Get Subscription Configuration Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Retrieves the configuration details for a specified Pub/Sub subscription. Ensure the subscription name is correctly formatted as 'projects/{project}/subscriptions/{sub}'. ```python from google import pubsub_v1 def sample_get_subscription(): # Create a client client = pubsub_v1.SubscriberClient() # Initialize request argument(s) request = pubsub_v1.GetSubscriptionRequest( subscription="subscription_value", ) # Make the request response = client.get_subscription(request=request) # Handle the response print(response) ``` -------------------------------- ### Get Topic Configuration Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Retrieve the configuration of a specific Pub/Sub topic. Ensure the topic name is correctly formatted as 'projects/{project}/topics/{topic}'. ```python from google import pubsub_v1 def sample_get_topic(): # Create a client client = pubsub_v1.PublisherClient() # Initialize request argument(s) request = pubsub_v1.GetTopicRequest( topic="topic_value", ) # Make the request response = client.get_topic(request=request) # Handle the response print(response) ``` -------------------------------- ### Create a Pub/Sub Subscription Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Use this snippet to create a new subscription to a Pub/Sub topic. Ensure you have the correct project and topic names. This example uses default client options; regional endpoints may be required for specific use cases. ```python from google import pubsub_v1 def sample_create_subscription(): # Create a client client = pubsub_v1.SubscriberClient() # Initialize request argument(s) request = pubsub_v1.Subscription( name="name_value", topic="topic_value", ) # Make the request response = client.create_subscription(request=request) # Handle the response print(response) ``` -------------------------------- ### Authenticate with JWT Credentials Source: https://github.com/googleapis/python-pubsub/blob/main/README.rst Shows how to authenticate Pub/Sub clients using JSON Web Tokens (JWT) by providing a google.auth.jwt.Credentials instance. This example configures credentials for both subscriber and publisher clients with appropriate audiences. ```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) ``` -------------------------------- ### Seek a subscription to a point in time or snapshot Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Use this snippet to seek an existing subscription. It requires a subscription name and can optionally specify a point in time or a snapshot. Ensure the subscription and snapshot are on the same topic. This example uses a placeholder for the subscription value and may require regional endpoint configuration. ```python from google import pubsub_v1 def sample_seek(): # Create a client client = pubsub_v1.SubscriberClient() # Initialize request argument(s) request = pubsub_v1.SeekRequest( subscription="subscription_value", ) # Make the request response = client.seek(request=request) # Handle the response print(response) ``` -------------------------------- ### Subscribe to messages from a Google Cloud Pub/Sub topic Source: https://github.com/googleapis/python-pubsub/blob/main/README.rst Sets up a subscription to a specified topic and configures a callback function to process incoming messages. This snippet only shows the setup and topic name definition. ```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. ) ``` -------------------------------- ### Install PortAudio on macOS Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/install_portaudio.tmpl.rst Use Homebrew to install PortAudio on macOS. This is a prerequisite for installing PyAudio. ```bash brew install portaudio ``` -------------------------------- ### Run Pub/Sub Sample Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/README.tmpl.rst Execute a Python Pub/Sub sample script from the command line. Ensure you have the necessary API enabled and role permissions. ```bash $ python sample.py ``` -------------------------------- ### Create Publisher Client from Service Account Info Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Instantiate a Publisher client using a dictionary containing service account credentials. Additional arguments can be passed to the constructor. ```python PublisherClient.from_service_account_info(info={'type': 'service_account', ...}) ``` -------------------------------- ### Publisher Sample Usage Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst Displays the usage instructions for the publisher.py script, outlining available commands and arguments. ```text usage: publisher.py [-h] project_id {list,create,delete,publish,publish-with-custom-attributes,publish-with-error-handler,publish-with-batch-settings,publish-with-retry-settings,publish-with-ordering-keys,resume-publish-with-ordering-keys,detach-subscription} ... ``` -------------------------------- ### Set IAM Policy JSON Example Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Example of a JSON object representing an IAM policy, used for setting access control on a Pub/Sub resource. ```json { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": ["user:eve@example.com"], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time <\n timestamp('2020-10-01T00:00:00.000Z')" } } ] } ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/googleapis/python-pubsub/blob/main/scripts/readme-gen/templates/install_deps.tmpl.rst Create a virtual environment named 'env' and activate it. Samples are compatible with Python 3.9+. ```bash virtualenv env source env/bin/activate ``` -------------------------------- ### Run the migration script Source: https://github.com/googleapis/python-pubsub/blob/main/UPGRADING.md Execute the `fixup_pubsub_v1_keywords.py` script to convert existing code. Provide input and output directories. ```bash $ scripts/fixup_pubsub_v1_keywords.py --input-directory .samples/ --output-directory samples/ ``` -------------------------------- ### IAM Policy JSON Structure Example Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md An example of an Identity and Access Management (IAM) policy structure in JSON format, defining role bindings and optional conditions. ```json { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": ["user:eve@example.com"], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < \ timestamp('2020-10-01T00:00:00.000Z')" } } ] } ``` -------------------------------- ### subscribe Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Asynchronously starts receiving messages on a given subscription. This method starts a background thread to pull messages and schedules them for processing using a provided callback. The callback is responsible for acknowledging or negatively acknowledging messages. ```APIDOC ## subscribe ### Description Asynchronously starts receiving messages on a given subscription. This method starts a background thread to begin pulling messages from a Pub/Sub subscription and scheduling them to be processed using the provided `callback`. The `callback` will be called with an individual `google.cloud.pubsub_v1.subscriber.message.Message`. It is the responsibility of the callback to either call `ack()` or `nack()` on the message when it finished processing. If an exception occurs in the callback during processing, the exception is logged and the message is `nack()`ed. ### Method subscribe ### Parameters #### Path Parameters - **subscription** (str) - Required - The subscription to receive messages from. - **callback** (Callable[[subscriber.message.Message], Any]) - Required - A function to be called with each message received. - **flow_control** (FlowControl | Sequence) - Optional - Used to control the rate at which messages are pulled. Defaults to conservative settings. - **scheduler** (subscriber.scheduler.ThreadScheduler | None) - Optional - A scheduler for processing messages. Defaults to a background thread. - **use_legacy_flow_control** (bool) - Optional - Disables server-side flow control enforcement, relying only on client-side flow control. Defaults to False. - **await_callbacks_on_shutdown** (bool) - Optional - Whether to wait for callbacks to complete on shutdown. Defaults to False. ### Response #### Success Response - **StreamingPullFuture** ([StreamingPullFuture](futures.md#google.cloud.pubsub_v1.subscriber.futures.StreamingPullFuture)) - A Future representing the execution of the receiver. Waiting on this future blocks until a non-recoverable error is encountered or the future is cancelled. ``` -------------------------------- ### Get Publisher Target Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Retrieves the target endpoint where the Pub/Sub API is located. ```python target: str ``` -------------------------------- ### Create Publisher Client from Service Account File Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Use this class method to create a Publisher client instance by providing the path to a service account JSON key file. It supports optional batch settings. ```python PublisherClient.from_service_account_file(filename='path/to/key.json') ``` -------------------------------- ### Create Subscriber Client from Service Account File Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Instantiate a Subscriber client using a service account private key JSON file. Additional arguments can be passed to the constructor. ```python from google.cloud import pubsub_v1 # TODO(developer): Construct the client with the service account file. # client = pubsub_v1.SubscriberClient.from_service_account_file("path/to/your/keyfile.json") # For more information, see https://cloud.google.com/docs/authentication/getting-started ``` -------------------------------- ### size property Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/message.md Gets the size of the underlying message in bytes. This property is useful for understanding the data volume of a message. ```APIDOC ## *property* size *: int* ### Description Return the size of the underlying message, in bytes. ``` -------------------------------- ### data Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/message.md Return the data for the underlying Pub/Sub Message. The data is always a bytestring; decode it to get a text string. ```APIDOC ## data ### Description Return the data for the underlying Pub/Sub Message. The data is always a bytestring; decode it to get a text string. ### Method N/A (Property access on an object) ### Endpoint N/A ### Returns The message data. ### Return type bytes ``` -------------------------------- ### Run Publisher Sample Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst Execute the main publisher Python script. This script provides a command-line interface for various publisher operations. ```bash python3 publisher.py ``` -------------------------------- ### Set Up Local Repository Remotes Source: https://github.com/googleapis/python-pubsub/blob/main/CONTRIBUTING.rst Configure your local repository to pull changes from the official googleapis/python-pubsub repository. ```bash $ git remote add upstream git@github.com:googleapis/python-pubsub.git $ git fetch upstream $ git merge upstream/main ``` -------------------------------- ### get_snapshot Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Gets the configuration details of a snapshot. Snapshots are used in Seek operations, which allow you to manage message acknowledgments in bulk. ```APIDOC ## get_snapshot ### Description Retrieves the configuration details for a specified snapshot. Snapshots are crucial for managing message acknowledgments in bulk, particularly for Seek operations that allow replaying messages based on a snapshot's state. ### Method subscriber.get_snapshot ### Parameters #### Request Body - **request** (google.pubsub_v1.types.GetSnapshotRequest | dict) - Optional - The request object for the GetSnapshot method. - **snapshot** (str) - Required - The name of the snapshot to retrieve. Must be in the format `projects/{project}/snapshots/{snap}`. This parameter is used if `request` is not provided. - **retry** (google.api_core.retry.Retry) - Optional - Specifies which errors should be retried. - **timeout** (float) - Optional - The duration in seconds for which the request is active. - **metadata** (Sequence[Tuple[str, Union[str, bytes]]]) - Optional - Key/value pairs to be sent as metadata with the request. Values for keys ending in '-bin' must be bytes. ### Response #### Success Response (200) - **Snapshot** (google.pubsub_v1.types.Snapshot) - A snapshot resource containing configuration details. ``` -------------------------------- ### google.cloud.pubsub_v1.publisher.futures.Future Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/futures.md Represents the result of an asynchronous Pub/Sub publishing operation. Clients can use this to get the message ID or any exceptions that occurred. ```APIDOC ## class google.cloud.pubsub_v1.publisher.futures.Future This future object is returned from asychronous Pub/Sub publishing calls. Calling [`result()`](#google.cloud.pubsub_v1.publisher.futures.Future.result) will resolve the future by returning the message ID, unless an error occurs. ### add_done_callback(callback: Callable[[Future], Any]) -> None Attach a callable that will be called when the future finishes. * **Parameters:** **callback** – A callable that will be called with this future as its only argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added. ### cancel() -> bool Actions in Pub/Sub generally may not be canceled. This method always returns `False`. ### cancelled() -> bool Actions in Pub/Sub generally may not be canceled. This method always returns `False`. ### done() -> bool Return True if the future was cancelled or finished executing. ### exception(timeout: Optional[float] = None) -> Optional[BaseException] Return the exception raised by the call that the future represents. * **Parameters:** **timeout** – The number of seconds to wait for the exception if the future isn’t done. If None, then there is no limit on the wait time. * **Returns:** The exception raised by the call that the future represents or None if the call completed without raising. * **Raises:** * **CancelledError** – If the future was cancelled. * **TimeoutError** – If the future didn’t finish executing before the given timeout. ### result(timeout: Optional[float] = None) -> str Return the message ID or raise an exception. This blocks until the message has been published successfully and returns the message ID unless an exception is raised. * **Parameters:** **timeout** – The number of seconds before this call times out and raises TimeoutError. * **Returns:** The message ID. * **Raises:** * **concurrent.futures.TimeoutError** – If the request times out. * **Exception** – For undefined exceptions in the underlying call execution. ### running() -> bool Return `True` if the associated Pub/Sub action has not yet completed. ``` -------------------------------- ### List Topics in a Project Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Demonstrates how to list all topics within a specified Google Cloud project using the Publisher client. Ensure you have the correct project ID and necessary authentication configured. ```python from google import pubsub_v1 def sample_list_topics(): # Create a client client = pubsub_v1.PublisherClient() # Initialize request argument(s) request = pubsub_v1.ListTopicsRequest( project="project_value", ) # Make the request page_result = client.list_topics(request=request) # Handle the response for response in page_result: print(response) ``` -------------------------------- ### Run Sample Tests Source: https://github.com/googleapis/python-pubsub/blob/main/CONTRIBUTING.rst Execute tests for code samples and snippets located in the 'samples/' directory. Ensure your environment is configured similarly to system tests. ```bash :: To run sample tests, you can execute:: ``` -------------------------------- ### Create Subscriber Client from Service Account Info Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Instantiate a Subscriber client using service account private key information. Additional arguments can be passed to the constructor. ```python from google.cloud import pubsub_v1 # TODO(developer): Construct the client with the service account info. # client = pubsub_v1.SubscriberClient.from_service_account_info(google_application_credentials_json) # For more information, see https://cloud.google.com/docs/authentication/getting-started ``` -------------------------------- ### Get IAM Policy for a Function Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Retrieves the IAM access control policy for a specific function. Returns an empty policy if none is set. ```python publisher_client.get_iam_policy(request={'resource': 'projects/my-project/topics/my-topic'}) ``` -------------------------------- ### Run IAM Snippet Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst This snippet shows how to execute the IAM demonstration script. It requires a Google Cloud project ID and specifies various IAM operations for topics and subscriptions. ```bash python3 iam.py ``` -------------------------------- ### Convert Pub/Sub API call from positional to request object Source: https://github.com/googleapis/python-pubsub/blob/main/docs/UPGRADING.md Example demonstrating the change in how API methods are called, moving from positional arguments to a request object. ```python from google.cloud import pubsub publisher = pubsub.PublisherClient() project_path = "projects/{}".format(PROJECT_ID) topics = publisher.list_topics(project_path) ``` ```python from google.cloud import pubsub publisher = pubsub.PublisherClient() project_path = f"projects/{PROJECT_ID}" topics = publisher.list_topics(request={"project": project_path}) ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/googleapis/python-pubsub/blob/main/CONTRIBUTING.rst Generate HTML documentation for the project using nox. This command is used to build and preview the documentation. ```bash $ nox -s docs ``` -------------------------------- ### Clone Python Pub/Sub Repository Source: https://github.com/googleapis/python-pubsub/blob/main/samples/snippets/README.rst Clone the python-docs-samples repository to your local machine. This is the first step to setting up the environment for running the samples. ```bash git clone https://github.com/googleapis/python-pubsub.git ``` -------------------------------- ### Get Message ID from Future Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/index.md Use the `.result()` method on the future to block until the publish operation is complete and retrieve the message ID. If an error occurs, an exception will be raised. ```python future = client.publish(topic, b'My awesome message.') message_id = future.result() ``` -------------------------------- ### Instantiate Publisher Client with Custom Settings Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Instantiate the PublisherClient with custom batch settings, publisher options including message ordering and flow control, and regional endpoint configuration. ```python from google.cloud import pubsub_v1 publisher_client = pubsub_v1.PublisherClient( # Optional batch_settings = pubsub_v1.types.BatchSettings( max_bytes=1024, # One kilobyte max_latency=1, # One second ), # Optional publisher_options = pubsub_v1.types.PublisherOptions( enable_message_ordering=False, flow_control=pubsub_v1.types.PublishFlowControl( message_limit=2000, limit_exceeded_behavior=pubsub_v1.types.LimitExceededBehavior.BLOCK, ), ), # Optional client_options = { "api_endpoint": REGIONAL_ENDPOINT } ) ``` -------------------------------- ### Invalid call mixing request object and keyword arguments Source: https://github.com/googleapis/python-pubsub/blob/main/docs/UPGRADING.md Shows an example of an invalid API call that mixes the `request` parameter with flattened keyword arguments, which will result in an error. ```python response = client.synthesize_speech( request={"project": project_path}, metadata=[("foo", "bar"), ("baz", "quux")], ) ``` -------------------------------- ### Start Asynchronous Subscription Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/index.md Initiates a background thread to receive messages from a Pub/Sub subscription and calls a specified callback function for each message. This method returns a StreamingPullFuture for managing the subscription. ```python # Wrap the following code in `with pubsub.SubscriberClient() as subscriber:` # Substitute PROJECT and SUBSCRIPTION with appropriate values for your # application. subscription_path = subscriber.subscription_path(PROJECT, SUBSCRIPTION) future = subscriber.subscribe(subscription_path, callback) ``` -------------------------------- ### Create a Pub/Sub Topic Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/publisher/api/client.md Demonstrates how to create a new topic using the PublisherClient. This requires initializing a Topic object with the desired name and making the create_topic request. Ensure the topic name adheres to the specified naming conventions. ```python from google import pubsub_v1 def sample_create_topic(): # Create a client client = pubsub_v1.PublisherClient() # Initialize request argument(s) request = pubsub_v1.Topic( name="name_value", ) # Make the request response = client.create_topic(request=request) # Handle the response print(response) ``` -------------------------------- ### Get IAM Policy for a Pub/Sub Subscription Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Retrieves the IAM access control policy for a given Pub/Sub subscription. Returns an empty policy if the subscription exists but has no policy set. ```python from google.cloud.pubsub_v1.types import GetIamPolicyRequest policy = subscriber.get_iam_policy(request=GetIamPolicyRequest(resource=subscription_path)) print(f"IAM Policy: {policy}") ``` -------------------------------- ### Get mTLS Endpoint and Certificate Source Source: https://github.com/googleapis/python-pubsub/blob/main/docs/pubsub/subscriber/api/client.md Retrieves the API endpoint and client certificate source for mutual TLS. This method is deprecated and its behavior depends on environment variables and client options. ```python from google.api_core.client_options import ClientOptions client_options = ClientOptions(api_endpoint="your.api.endpoint.com") endpoint, cert_source = subscriber.get_mtls_endpoint_and_cert_source(client_options) print(f"mTLS Endpoint: {endpoint}") ```