Connect your Python applications to Cloudera Operational Database

You can connect your applications written in Python programming language to a CDP Operational Database (COD) through Phoenix.

Before you write an application to connect to COD, do the following:

This application code is an example of validating your connection to COD.

import phoenixdb
import configparser

class Database:

    def connect(self):
        REQUIRED_OPTS = ['Username', 'Password', 'Url']
        config = configparser.ConfigParser()'config.ini')
        if not 'COD' in config:
            raise Exception("Could not find section for COD in config.ini")
        cod_config = config['COD']
        opts = {}

        # Validate the configuration
        for required_opt in REQUIRED_OPTS:
            if not required_opt in cod_config:
                raise Exception("Did not find %s in configuration" % (required_opt))    
      # Provide non-required options
        if 'Truststore' in cod_config:
            opts['verify'] = cod_config['Truststore']
        if 'Authentication' in cod_config:
            opts['authentication'] = cod_config['Authentication']
            opts['authentication'] = 'BASIC'

        # Read required options
        opts['avatica_user'] = cod_config['Username']
        opts['avatica_password'] = cod_config['Password']
        return phoenixdb.connect(cod_config['Url'], autocommit=True, **opts)

This code is an example of creating a table and adding data to a COD instance.

import phoenixdb
from database import Database

def load():
    db = Database()
    conn = db.connect()

    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username VARCHAR)")
    cursor.execute("UPSERT INTO users VALUES (?, ?)", (1, 'admin'))
    cursor.execute("SELECT * FROM users")

if __name__ == '__main__':