Pulsar Python client

Pulsar Python client library is a wrapper over the existing C++ client library and exposes all of the same features. You can find the code in the Python directory of the C++ client code.

All the methods in producer, consumer, and reader of a Python client are thread-safe.

pdoc-generated API docs for the Python client are available here.

Install

You can install the pulsar-client library either via PyPi, using pip, or by building the library from source.

Install using pip

To install the pulsar-client library as a pre-built package using the pip package manager:

  1. $ pip install pulsar-client==2.10.0

Optional dependencies

If you install the client libraries on Linux to support services like Pulsar functions or Avro serialization, you can install optional components alongside the pulsar-client library.

  1. # avro serialization
  2. $ pip install pulsar-client[avro]=='2.10.0'
  3. # functions runtime
  4. $ pip install pulsar-client[functions]=='2.10.0'
  5. # all optional components
  6. $ pip install pulsar-client[all]=='2.10.0'

Installation via PyPi is available for the following Python versions:

PlatformSupported Python versions
MacOS
10.13 (High Sierra), 10.14 (Mojave)
2.7, 3.7, 3.8, 3.9
Linux2.7, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9

Install from source

To install the pulsar-client library by building from source, follow instructions and compile the Pulsar C++ client library. That builds the Python binding for the library.

To install the built Python bindings:

  1. $ git clone https://github.com/apache/pulsar
  2. $ cd pulsar/pulsar-client-cpp/python
  3. $ sudo python setup.py install

API Reference

The complete Python API reference is available at api/python.

Examples

You can find a variety of Python code examples for the pulsar-client library.

Producer example

The following example creates a Python producer for the my-topic topic and sends 10 messages on that topic:

  1. import pulsar
  2. client = pulsar.Client('pulsar://localhost:6650')
  3. producer = client.create_producer('my-topic')
  4. for i in range(10):
  5. producer.send(('Hello-%d' % i).encode('utf-8'))
  6. client.close()

Consumer example

The following example creates a consumer with the my-subscription subscription name on the my-topic topic, receives incoming messages, prints the content and ID of messages that arrive, and acknowledges each message to the Pulsar broker.

  1. import pulsar
  2. client = pulsar.Client('pulsar://localhost:6650')
  3. consumer = client.subscribe('my-topic', 'my-subscription')
  4. while True:
  5. msg = consumer.receive()
  6. try:
  7. print("Received message '{}' id='{}'".format(msg.data(), msg.message_id()))
  8. # Acknowledge successful processing of the message
  9. consumer.acknowledge(msg)
  10. except Exception:
  11. # Message failed to be processed
  12. consumer.negative_acknowledge(msg)
  13. client.close()

This example shows how to configure negative acknowledgement.

  1. from pulsar import Client, schema
  2. client = Client('pulsar://localhost:6650')
  3. consumer = client.subscribe('negative_acks','test',schema=schema.StringSchema())
  4. producer = client.create_producer('negative_acks',schema=schema.StringSchema())
  5. for i in range(10):
  6. print('send msg "hello-%d"' % i)
  7. producer.send_async('hello-%d' % i, callback=None)
  8. producer.flush()
  9. for i in range(10):
  10. msg = consumer.receive()
  11. consumer.negative_acknowledge(msg)
  12. print('receive and nack msg "%s"' % msg.data())
  13. for i in range(10):
  14. msg = consumer.receive()
  15. consumer.acknowledge(msg)
  16. print('receive and ack msg "%s"' % msg.data())
  17. try:
  18. # No more messages expected
  19. msg = consumer.receive(100)
  20. except:
  21. print("no more msg")
  22. pass

Reader interface example

You can use the Pulsar Python API to use the Pulsar reader interface. Here’s an example:

  1. # MessageId taken from a previously fetched message
  2. msg_id = msg.message_id()
  3. reader = client.create_reader('my-topic', msg_id)
  4. while True:
  5. msg = reader.read_next()
  6. print("Received message '{}' id='{}'".format(msg.data(), msg.message_id()))
  7. # No acknowledgment

Multi-topic subscriptions

In addition to subscribing a consumer to a single Pulsar topic, you can also subscribe to multiple topics simultaneously. To use multi-topic subscriptions, you can supply a regular expression (regex) or a List of topics. If you select topics via regex, all topics must be within the same Pulsar namespace.

The following is an example:

  1. import re
  2. consumer = client.subscribe(re.compile('persistent://public/default/topic-*'), 'my-subscription')
  3. while True:
  4. msg = consumer.receive()
  5. try:
  6. print("Received message '{}' id='{}'".format(msg.data(), msg.message_id()))
  7. # Acknowledge successful processing of the message
  8. consumer.acknowledge(msg)
  9. except Exception:
  10. # Message failed to be processed
  11. consumer.negative_acknowledge(msg)
  12. client.close()

Schema

Supported schema types

You can use different builtin schema types in Pulsar. All the definitions are in the pulsar.schema package.

SchemaNotes
BytesSchemaGet the raw payload as a bytes object. No serialization/deserialization are performed. This is the default schema mode
StringSchemaEncode/decode payload as a UTF-8 string. Uses str objects
JsonSchemaRequire record definition. Serializes the record into standard JSON payload
AvroSchemaRequire record definition. Serializes in AVRO format

Schema definition reference

The schema definition is done through a class that inherits from pulsar.schema.Record.

This class has a number of fields which can be of either pulsar.schema.Field type or another nested Record. All the fields are specified in the pulsar.schema package. The fields are matching the AVRO fields types.

Field TypePython TypeNotes
Booleanbool
Integerint
Longint
Floatfloat
Doublefloat
Bytesbytes
Stringstr
ArraylistNeed to specify record type for items.
MapdictKey is always String. Need to specify value type.

Additionally, any Python Enum type can be used as a valid field type.

Fields parameters

When adding a field, you can use these parameters in the constructor.

ArgumentDefaultNotes
defaultNoneSet a default value for the field. Eg: a = Integer(default=5)
requiredFalseMark the field as “required”. It is set in the schema accordingly.

Schema definition examples

Simple definition
  1. class Example(Record):
  2. a = String()
  3. b = Integer()
  4. c = Array(String())
  5. i = Map(String())
Using enums
  1. from enum import Enum
  2. class Color(Enum):
  3. red = 1
  4. green = 2
  5. blue = 3
  6. class Example(Record):
  7. name = String()
  8. color = Color
Complex types
  1. class MySubRecord(Record):
  2. x = Integer()
  3. y = Long()
  4. z = String()
  5. class Example(Record):
  6. a = String()
  7. sub = MySubRecord()
Set namespace for Avro schema

Set the namespace for Avro Record schema using the special field _avro_namespace.

  1. class NamespaceDemo(Record):
  2. _avro_namespace = 'xxx.xxx.xxx'
  3. x = String()
  4. y = Integer()

The schema definition is like this.

  1. {
  2. 'name': 'NamespaceDemo', 'namespace': 'xxx.xxx.xxx', 'type': 'record', 'fields': [
  3. {'name': 'x', 'type': ['null', 'string']},
  4. {'name': 'y', 'type': ['null', 'int']}
  5. ]
  6. }

Declare and validate schema

You can send messages using BytesSchema, StringSchema, AvroSchema, and JsonSchema.

Before the producer is created, the Pulsar broker validates that the existing topic schema is the correct type and that the format is compatible with the schema definition of a class. If the format of the topic schema is incompatible with the schema definition, an exception occurs in the producer creation.

Once a producer is created with a certain schema definition, it only accepts objects that are instances of the declared schema class.

Similarly, for a consumer or reader, the consumer returns an object (which is an instance of the schema record class) rather than raw bytes.

Example

  1. consumer = client.subscribe(
  2. topic='my-topic',
  3. subscription_name='my-subscription',
  4. schema=AvroSchema(Example) )
  5. while True:
  6. msg = consumer.receive()
  7. ex = msg.value()
  8. try:
  9. print("Received message a={} b={} c={}".format(ex.a, ex.b, ex.c))
  10. # Acknowledge successful processing of the message
  11. consumer.acknowledge(msg)
  12. except Exception:
  13. # Message failed to be processed
  14. consumer.negative_acknowledge(msg)
  • BytesSchema
  • StringSchema
  • AvroSchema
  • JsonSchema

You can send byte data using a BytesSchema.

Example

  1. producer = client.create_producer(
  2. 'bytes-schema-topic',
  3. schema=BytesSchema())
  4. producer.send(b"Hello")
  5. consumer = client.subscribe(
  6. 'bytes-schema-topic',
  7. 'sub',
  8. schema=BytesSchema())
  9. msg = consumer.receive()
  10. data = msg.value()

You can send string data using a StringSchema.

Example

  1. producer = client.create_producer(
  2. 'string-schema-topic',
  3. schema=StringSchema())
  4. producer.send("Hello")
  5. consumer = client.subscribe(
  6. 'string-schema-topic',
  7. 'sub',
  8. schema=StringSchema())
  9. msg = consumer.receive()
  10. str = msg.value()

You can declare an AvroSchema using one of the following methods.

Method 1: Record

You can declare an AvroSchema by passing a class that inherits from pulsar.schema.Record and defines the fields as class variables.

Example

  1. class Example(Record):
  2. a = Integer()
  3. b = Integer()
  4. producer = client.create_producer(
  5. 'avro-schema-topic',
  6. schema=AvroSchema(Example))
  7. r = Example(a=1, b=2)
  8. producer.send(r)
  9. consumer = client.subscribe(
  10. 'avro-schema-topic',
  11. 'sub',
  12. schema=AvroSchema(Example))
  13. msg = consumer.receive()
  14. e = msg.value()

Method 2: JSON definition

You can declare an AvroSchema using JSON. In this case, Avro schemas are defined using JSON.

Example

Below is an AvroSchema defined using a JSON file (company.avsc).

  1. {
  2. "doc": "this is doc",
  3. "namespace": "example.avro",
  4. "type": "record",
  5. "name": "Company",
  6. "fields": [
  7. {"name": "name", "type": ["null", "string"]},
  8. {"name": "address", "type": ["null", "string"]},
  9. {"name": "employees", "type": ["null", {"type": "array", "items": {
  10. "type": "record",
  11. "name": "Employee",
  12. "fields": [
  13. {"name": "name", "type": ["null", "string"]},
  14. {"name": "age", "type": ["null", "int"]}
  15. ]
  16. }}]},
  17. {"name": "labels", "type": ["null", {"type": "map", "values": "string"}]}
  18. ]
  19. }

You can load a schema definition from file by using [avro.schema]((http://avro.apache.org/docs/current/gettingstartedpython.html) or fastavro.schema.

If you use the “JSON definition” method to declare an AvroSchema, pay attention to the following points:

  • You need to use Python dict to produce and consume messages, which is different from using the “Record” method.

  • When generating an AvroSchema object, set _record_cls parameter to None.

Example

  1. from fastavro.schema import load_schema
  2. from pulsar.schema import *
  3. schema_definition = load_schema("examples/company.avsc")
  4. avro_schema = AvroSchema(None, schema_definition=schema_definition)
  5. producer = client.create_producer(
  6. topic=topic,
  7. schema=avro_schema)
  8. consumer = client.subscribe(topic, 'test', schema=avro_schema)
  9. company = {
  10. "name": "company-name" + str(i),
  11. "address": 'xxx road xxx street ' + str(i),
  12. "employees": [
  13. {"name": "user" + str(i), "age": 20 + i},
  14. {"name": "user" + str(i), "age": 30 + i},
  15. {"name": "user" + str(i), "age": 35 + i},
  16. ],
  17. "labels": {
  18. "industry": "software" + str(i),
  19. "scale": ">100",
  20. "funds": "1000000.0"
  21. }
  22. }
  23. producer.send(company)
  24. msg = consumer.receive()
  25. # Users could get a dict object by `value()` method.
  26. msg.value()

Record

You can declare a JsonSchema by passing a class that inherits from pulsar.schema.Record and defines the fields as class variables. This is similar to using AvroSchema. The only difference is to use JsonSchema instead of AvroSchema when defining schema type as shown below. For how to use AvroSchema via record, see here.

  1. producer = client.create_producer(
  2. 'avro-schema-topic',
  3. schema=JsonSchema(Example))
  4. consumer = client.subscribe(
  5. 'avro-schema-topic',
  6. 'sub',
  7. schema=JsonSchema(Example))

End-to-end encryption

End-to-end encryption allows applications to encrypt messages at producers and decrypt messages at consumers.

Configuration

To use the end-to-end encryption feature in the Python client, you need to configure publicKeyPath and privateKeyPath for both producer and consumer.

  1. publicKeyPath: "./public.pem"
  2. privateKeyPath: "./private.pem"

Tutorial

This section provides step-by-step instructions on how to use the end-to-end encryption feature in the Python client.

Prerequisite

  • Pulsar Python client 2.7.1 or later

Step

  1. Create both public and private key pairs.

    Input

    1. openssl genrsa -out private.pem 2048
    2. openssl rsa -in private.pem -pubout -out public.pem
  1. Create a producer to send encrypted messages.

    Input

    1. import pulsar
    2. publicKeyPath = "./public.pem"
    3. privateKeyPath = "./private.pem"
    4. crypto_key_reader = pulsar.CryptoKeyReader(publicKeyPath, privateKeyPath)
    5. client = pulsar.Client('pulsar://localhost:6650')
    6. producer = client.create_producer(topic='encryption', encryption_key='encryption', crypto_key_reader=crypto_key_reader)
    7. producer.send('encryption message'.encode('utf8'))
    8. print('sent message')
    9. producer.close()
    10. client.close()
  1. Create a consumer to receive encrypted messages.

    Input

    1. import pulsar
    2. publicKeyPath = "./public.pem"
    3. privateKeyPath = "./private.pem"
    4. crypto_key_reader = pulsar.CryptoKeyReader(publicKeyPath, privateKeyPath)
    5. client = pulsar.Client('pulsar://localhost:6650')
    6. consumer = client.subscribe(topic='encryption', subscription_name='encryption-sub', crypto_key_reader=crypto_key_reader)
    7. msg = consumer.receive()
    8. print("Received msg '{}' id = '{}'".format(msg.data(), msg.message_id()))
    9. consumer.close()
    10. client.close()
  1. Run the consumer to receive encrypted messages.

    Input

    1. python consumer.py
  1. In a new terminal tab, run the producer to produce encrypted messages.

    Input

    1. python producer.py
  1. Now you can see the producer sends messages and the consumer receives messages successfully.
  2. **Output**
  3. This is from the producer side.
  4. ```
  5. sent message
  6. ```
  7. This is from the consumer side.
  8. ```
  9. Received msg 'encryption message' id = '(0,0,-1,-1)'
  10. ```