Python Redis programming

Enable the default connection in Dashboard and then any programming feature that Redis offers will be available to your services via the underlying redis-py library, as in the examples below.

Simple keys

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class MyService(Service):

    def handle(self):
        self.kvdb.conn.set('my-key', 'my-value')
        self.logger.info(self.kvdb.conn.get('my-key'))
INFO - my-value

Lists

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class MyService(Service):

    def handle(self):

        # Clear/delete the list
        self.kvdb.conn.delete('my-list')

        # Push 10 elements
        for x in range(10):
            self.kvdb.conn.lpush('my-list', x)

        # Read them back
        self.logger.info(self.kvdb.conn.lrange('my-list', 0, 9999))
INFO - ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']

Dictionaries (hashmaps)

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class MyService(Service):

    def handle(self):

        # Clear/delete the dictionary
        self.kvdb.conn.delete('my-dict')

        # Set 10 keys and values
        for x in range(10):
            self.kvdb.conn.hset('my-dict', x, x**x)

        # Read one of them back
        self.logger.info(self.kvdb.conn.hget('my-dict', 7))
INFO - 823543

Transactions

Pipelines can be used to improve performance of the execution of multiple operations and to invoke the operations atomically.

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class MyService(Service):

    def handle(self):

        # Either deletes all the keys specified and adds a new one or none
        # of it is performed.
        with self.kvdb.conn.pipeline() as p:

            # Deletes
            p.delete('my-key-1')
            p.delete('my-key-2')
            p.delete('my-key-3')

            # Add new key
            p.set('my-key-4', 'my-value')

            # Execute all the commands queued up in a single transaction
            p.execute()


Schedule a meaningful demo

Book a demo with an expert who will help you build meaningful systems that match your ambitions

"For me, Zato Source is the only technology partner to help with operational improvements."

— John Adams
Program Manager of Channel Enablement at Keysight