PubNub Python SDK

repository·master·Indexed 41 days ago

https://github.com/pubnub/python

A high-level interface for building real-time applications with data transmission, presence, and messaging. Supports Python 3.7 through 3.10 and provides both Native (threading) and AsyncIO implementations. Key features include the PNConfiguration for client setup, SubscribeCallback for event handling, and methods for publishing and subscribing to channels.

Tokens
1.8K
Snippets
8
Records
11
Agent score
50%

What's inside PubNub

  1. Use the Native (threading) implementation

    master

    The Native implementation uses the requests library. It supports both synchronous and asynchronous execution patterns:

    Synchronous calls

    Use the sync() method. This returns an Envelope object which wraps both the Result and the Status. Exceptions are raised natively using the raise Exception syntax.

    Asynchronous calls

    Use the async() function. You must pass a callback function which will be invoked with either a response or an error.

    # Example of the conceptual pattern for async calls
    pubnub.async(callback_function, ...)
  2. Supported Python versions and platforms

    master

    Python Versions

    Supported versions: 3.7, 3.8, 3.9, 3.10.

    Platforms

    • Ubuntu: Primary supported platform (tested via Travis.CI).
    • Windows/MacOS/BSD: Support has been verified, but newer releases have not been explicitly tested on these platforms.
  3. Configure the PubNub client

    master

    To initialize the PubNub client, create a PNConfiguration object, set your subscribe_key, publish_key, and a unique uuid, then pass this configuration to the PubNub class.

    pnconfig = PNConfiguration()
    
    pnconfig.subscribe_key = 'mySubscribeKey'
    pnconfig.publish_key = 'myPublishKey'
    pnconfig.uuid = 'myUniqueUUID'
    pubnub = PubNub(pnconfig)
  4. Add event listeners using SubscribeCallback

    master

    To handle real-time events like messages, presence, or status changes, extend the SubscribeCallback class and implement the desired methods. Once implemented, register your handler using pubnub.add_listener().

    Available methods to override:

    • status(self, pubnub, event): Handles status and error events. The event object contains details such as is_error(), category, error_data, error, status_code, operation, tls_enabled, uuid, auth_key, origin, client_request, client_response, original_response, affected_channels, and affected_groups.
    • presence(self, pubnub, presence): Handles incoming presence data.
    • message(self, pubnub, message): Handles incoming messages.
    • signal(self, pubnub, signal): Handles incoming signals.
    class SubscribeHandler(SubscribeCallback):
      def status(self, pubnub, event):
        print("Is there an error? ", event.is_error())
        print("Status value for category: %s" % event.category)
        # ... other event properties
    
      def presence(self, pubnub, presence):
          pass  # Handle incoming presence data
    
      def message(self, pubnub, message):
          pass  # Handle incoming messages
    
      def signal(self, pubnub, signal):
          pass # Handle incoming signals
    
    pubnub.add_listener(SubscribeHandler())
  5. Run the AsyncIO PubNub Subscribe Example

    master

    This example demonstrates how to use the PubNub Python SDK with asyncio to subscribe to a channel and listen for messages.

    To run the example, you need to install the required dependencies and set your PubNub credentials as environment variables. For testing purposes, the demo keys can be used.

    Prerequisites:

    • asyncio
    • pubnub

    Setup steps:

    1. Install dependencies using pip.
    2. Export PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY.
    3. Execute the main.py script.
    pip install asyncio pubnub
    export PUBNUB_PUBLISH_KEY=demo
    export PUBNUB_SUBSCRIBE_KEY=demo
    python main.py
  6. Configure Daemon mode for the Native SDK

    master

    By default, daemon mode is disabled for all requests. When disabled, asynchronous requests will block the main thread until all child processes/threads are closed. To enable Java-like behavior—where the program can continue execution without waiting for response completion—explicitly set daemon to True in the PubNub configuration.

    pubnub.config.daemon = True
  7. Publish and Subscribe to channels

    master

    Publishing a message

    Use the .publish() method to send data to a channel. You can use .pn_async(callback) to provide a callback function that handles the result or error via an envelope and status object.

    Subscribing to channels

    Use the .subscribe() method to listen for messages on specific channels using .channels('channel_name') and call .execute() to start the subscription.

    Note: The status object in the publish callback provides an is_error() method to check for success.

    def my_publish_callback(envelope, status):
      if status.is_error():
        ... #handle error here
      else:
        ... #handle result here
    
    pubnub.publish().channel('my_channel').message('Hello world!').pn_async(my_publish_callback)
    
    pubnub.subscribe().channels('my_channel').execute()
  8. Publish a message to a channel via curl

    master

    You can trigger a message to be received by an AsyncIO subscriber by using a curl command to hit the PubNub REST API publish endpoint. This is useful for testing subscriptions without writing a separate publisher script.

    Use the following format: curl "https://ps.pndsn.com/publish/${PUBNUB_PUBLISH_KEY}/${PUBNUB_SUBSCRIBE_KEY}/0/${CHANNEL}/0/%22${MESSAGE}%22"

    export PUBNUB_PUBLISH_KEY=demo
    export PUBNUB_SUBSCRIBE_KEY=demo
    curl "https://ps.pndsn.com/publish/${PUBNUB_PUBLISH_KEY}/${PUBNUB_SUBSCRIBE_KEY}/0/my_channel/0/%22Hello%20World%22"
  9. Use the Asyncio implementation

    master

    The SDK supports the asyncio library. There are two ways to invoke calls:

    1. Using result(): Returns only the result. If an exception occurs, it is raised natively.
    2. Using future(): Returns an Envelope (a wrapper for the result and status). In the event of an exception, you can check the status using the env.is_error() method.
  10. Use SubscribeListener for testing

    master
    SubscribeListener objects are helper classes designed to simplify testing behavior across all implementations. While they are available for end-users, they are considered unofficial, are not well-tested, and are not covered in the primary documentation.