Skip to content
John Maguire edited this page Nov 15, 2020 · 1 revision

Cardinal ships with an extremely lightweight solution for persistent data using flat JSON files.

Defining a database

Define your database(s) in your plugin's constructor. It's recommended to use the plugin name as your DB name to avoid any conflicts. For example:

class WeatherPlugin(object):
    def __init__(self, cardinal):
        self.db = cardinal.get_db('weather')

get_db() supports a couple of additional options:

get_db(self, name, network_specific=True, default=None):

By default, a separate database will be created per network Cardinal connects to. If you'd rather share a single database across all networks, simply pass network_specific=False. Also by default, the database will be an empty JSON object ({}). You can specify a more complex default using the default argument.

Using the database

Inside your plugin, the database can be accessed by using the member instance you defined in your constructor as a context manager:

    @command('setw')
    def set_weather(self, cardinal, user, channel, msg):
        try:
            location = msg.split(' ', 1)[1]
        except IndexError:
            return

        with self.db() as db:
            db[user.nick] = location

When the with block is executed, your database will be loaded into the variable you specify after as. When the with block finishes, the changes will be persisted to the filesystem.