Python Scripting
(→Accessing Resources) |
(→Accessing Resources) |
||
Line 7: | Line 7: | ||
DreamFactory passes in two [[DreamFactory/Features/Scripting#Resources Available To A Script|additional objects]] for use in the scripts. | DreamFactory passes in two [[DreamFactory/Features/Scripting#Resources Available To A Script|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. | In Python, these resources are represented as native dictionaries and can be accessed as normal. See the examples below. | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
Using the '''event''' resource... | Using the '''event''' resource... | ||
Line 54: | Line 48: | ||
return result; | return result; | ||
+ | </pre> | ||
+ | |||
+ | Using the '''platform''' resource... | ||
+ | <pre> | ||
+ | apiKey = platform['session']['api_key']; | ||
+ | jwt = platform['session']['session_token']; | ||
</pre> | </pre> |
Revision as of 00:10, 16 July 2016
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 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;
Using the platform resource...
apiKey = platform['session']['api_key']; jwt = platform['session']['session_token'];