{"id":9312,"library":"solace-pubsubplus","title":"Solace PubSub+ Python API","description":"The `solace-pubsubplus` library provides a Python API for interacting with Solace PubSub+ event brokers. It supports publishing and subscribing to messages, managing topics, queues, and handling various messaging patterns. Currently at version 1.11.0, it follows a regular release cadence with updates for new features and bug fixes, typically aligning with Solace PubSub+ broker releases.","status":"active","version":"1.11.0","language":"en","source_language":"en","source_url":"https://github.com/SolaceProducts/solace-pubsubplus-client-python","tags":["messaging","pubsub","solace","event-streaming","mqtt","amqp"],"install":[{"cmd":"pip install solace-pubsubplus","lang":"bash","label":"Install latest version"}],"dependencies":[],"imports":[{"symbol":"SolaceSession","correct":"from solace_pubsubplus import SolaceSession"},{"symbol":"Message","correct":"from solace_pubsubplus import Message"},{"symbol":"Subscription","correct":"from solace_pubsubplus import Subscription"},{"symbol":"SolaceSessionProperties","correct":"from solace_pubsubplus import SolaceSessionProperties"},{"symbol":"DeliveryMode","correct":"from solace_pubsubplus import DeliveryMode"}],"quickstart":{"code":"import os\nimport time\nimport threading\nfrom solace_pubsubplus import SolaceSession, SolaceSessionProperties, Message, MessageBuilder, DeliveryMode, Subscription, SubscribeFlags, SolaceLogLevel\n\n# Configuration from environment variables\nSOLACE_HOST = os.environ.get(\"SOLACE_HOST\", \"localhost:55555\") # e.g., 'tcp://your_broker_host:55555'\nSOLACE_VPN = os.environ.get(\"SOLACE_VPN\", \"default\")\nSOLACE_USERNAME = os.environ.get(\"SOLACE_USERNAME\", \"username\")\nSOLACE_PASSWORD = os.environ.get(\"SOLACE_PASSWORD\", \"password\")\n\nTOPIC_NAME = \"python/quickstart/hello\"\n\n# Global lock for thread-safe printing\nprint_lock = threading.Lock()\n\ndef on_message_received(message: Message):\n    \"\"\"Callback function for received messages.\"\"\"\n    with print_lock:\n        print(f\"Received message on topic '{message.get_destination_as_topic()}'\")\n        if message.get_data():\n            print(f\"Message data: {message.get_data().decode('utf-8')}\")\n\ndef run_quickstart():\n    # 1. Configure Solace Session Properties\n    session_properties = SolaceSessionProperties()\n    session_properties.host = SOLACE_HOST\n    session_properties.vpn_name = SOLACE_VPN\n    session_properties.username = SOLACE_USERNAME\n    session_properties.password = SOLACE_PASSWORD\n    session_properties.connect_retries = 3\n    session_properties.reconnect_retries = 3\n\n    # Set log level for more detailed output (optional)\n    SolaceSession.set_log_level(SolaceLogLevel.INFO)\n\n    session = None\n    try:\n        # 2. Create and Connect the Solace Session\n        session = SolaceSession(session_properties)\n        session.connect()\n        with print_lock:\n            print(f\"Connected to Solace PubSub+ broker at {SOLACE_HOST}\")\n\n        # 3. Set up Message Callback\n        session.set_message_receive_callback(on_message_received)\n\n        # 4. Subscribe to a Topic\n        subscription = Subscription(TOPIC_NAME)\n        session.subscribe(subscription, SubscribeFlags.WAIT_FOR_CONFIRM)\n        with print_lock:\n            print(f\"Subscribed to topic '{TOPIC_NAME}'\")\n\n        # 5. Publish a Message\n        message_builder = MessageBuilder()\n        message = message_builder \\\n            .with_delivery_mode(DeliveryMode.DIRECT) \\\n            .with_topic(TOPIC_NAME) \\\n            .with_property(\"user-property\", \"value\") \\\n            .build()\n        message.set_data(f\"Hello from Python Quickstart! Timestamp: {time.time()}\".encode('utf-8'))\n\n        session.publish(message)\n        with print_lock:\n            print(f\"Published message to topic '{TOPIC_NAME}'\")\n\n        # 6. Wait briefly for the message to be received (if publishing to self)\n        time.sleep(2)\n\n    except Exception as e:\n        with print_lock:\n            print(f\"An error occurred: {e}\")\n    finally:\n        if session:\n            # 7. Disconnect the Session\n            with print_lock:\n                print(\"Disconnecting Solace Session...\")\n            session.disconnect()\n            with print_lock:\n                print(\"Disconnected.\")\n\nif __name__ == \"__main__\":\n    run_quickstart()","lang":"python","description":"This quickstart demonstrates how to connect to a Solace PubSub+ broker, subscribe to a topic, publish a direct message, and receive messages using a callback function. Ensure `SOLACE_HOST`, `SOLACE_VPN`, `SOLACE_USERNAME`, and `SOLACE_PASSWORD` environment variables are set or updated in the script."},"warnings":[{"fix":"Access the `SolaceSession` instance from a dedicated thread or use appropriate threading primitives (e.g., locks) if multiple threads need to interact with it.","message":"The SolaceSession object is generally not thread-safe. Interactions with the session (connect, disconnect, publish, subscribe, etc.) should be performed from a single thread or carefully synchronized to avoid race conditions and undefined behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Keep message callbacks short and non-blocking. If significant processing is required, dispatch the message to a separate worker thread or queue for asynchronous handling.","message":"Message receive callbacks execute on an internal client thread. Blocking operations within these callbacks can prevent other messages from being processed or halt the client's internal event loop, leading to performance issues or deadlocks.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always explicitly set `DeliveryMode` using `MessageBuilder.with_delivery_mode()` based on your application's reliability requirements.","message":"It's crucial to explicitly manage the `DeliveryMode` for messages. `DeliveryMode.DIRECT` offers high performance but no guaranteed delivery, while `DeliveryMode.PERSISTENT` ensures guaranteed delivery but with higher overhead. The default might be `DIRECT`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always ensure `session.disconnect()` is called, typically within a `finally` block, to release resources and inform the broker of client departure.","message":"Forgetting to call `session.disconnect()` can leave open connections, consume broker resources, and prevent the client from gracefully cleaning up.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Verify that the Solace PubSub+ broker is running and accessible. Check the `SOLACE_HOST` and `SOLACE_VPN` settings for typos (e.g., ensure host includes the port like `localhost:55555`). Review firewall rules on both client and broker machines.","cause":"The Solace PubSub+ broker is either not running, the provided host/port is incorrect, or a firewall is blocking the connection.","error":"solace_pubsubplus.SolaceConnectionException: Connection refused"},{"fix":"Double-check the `SOLACE_USERNAME`, `SOLACE_PASSWORD`, and `SOLACE_VPN` values against your broker's configuration. Ensure the user has permissions to connect to the specified VPN.","cause":"The username, password, or VPN name provided in the `SolaceSessionProperties` is incorrect or unauthorized.","error":"solace_pubsubplus.SolaceAuthenticationException: Authentication failed"},{"fix":"Install the package using pip: `pip install solace-pubsubplus`.","cause":"The `solace-pubsubplus` package has not been installed in the current Python environment.","error":"ModuleNotFoundError: No module named 'solace_pubsubplus'"},{"fix":"Ensure that your application logic does not attempt to subscribe to the same topic multiple times on the same session. If dynamic topic changes are needed, explicitly unsubscribe before resubscribing.","cause":"An attempt was made to subscribe to a topic that the session is already subscribed to.","error":"solace_pubsubplus.SolaceOperationException: Subscription already exists"}]}