Python Scripting

From DreamFactory
Jump to: navigation, search

DreamFactory supports writing event scripts and custom scripting service scripts in Python. Note: These scripts are not sandboxed like V8js so care must be taken to prevent unwanted access to system resources, e.g, the file system of the host server that is running DreamFactory. Please see example scripts for Python for more information. Python needs to installed on the host server to run your Python scripts.

NOTE: DreamFactory Python scripting requires 'bunch' package to be installed on server. sudo pip install bunch

Accessing Resources

DreamFactory passes in two additional objects for use in the scripts. In Python, these resources are represented as native dictionaries and can be accessed as normal. See the examples below.

Using the platform resource...

apiKey = platform['session']['api_key'];
jwt = platform['session']['session_token'];

Using the event resource...

verb = event['request']['method'];

if verb != 'GET':
    raise Exception('Only HTTP GET is allowed on this endpoint.');
    
# get resource, /math —> "", /math/add —> "add"
resource = event['resource'];

# get query params from request
params = event['request']['parameters'];

required = ['n1', 'n2'];

if resource != "":
    for element in required:
        if params.get(element, "") == "":
            raise Exception('Missing ' + element + ' in params.');
    
    n1 = float(params['n1']);
    n2 = float(params['n2']);
    
if resource == "":
    # /math means return all supported resources
    result = {'resource':['add', 'subtract', 'multiply', 'divide']};
elif resource == "add":
    result = {'result':(n1+n2)};
elif resource == "subtract":
    result = {'result':(n1-n2)};
elif resource == "multiply":
    result = {'result':(n1*n2)};
elif resource == "divide":
    if n2 == 0:
        raise Exception('Divide by zero error.');
    result = {'result':(n1/n2)};
else:
    raise Exception('Invalid or missing resource name.');

return result;