Python Field validation example

From DreamFactory
Jump to: navigation, search
DreamFactoryTutorialsPython Field validation example
 
Line 7: Line 7:
 
# This script runs BEFORE records are written to the db.
 
# This script runs BEFORE records are written to the db.
 
   
 
   
payload = event.request.payload;
+
payload = event.request.payload
 
   
 
   
 
if(payload.resource):
 
if(payload.resource):
 
     for record in payload.resource:
 
     for record in payload.resource:
 
         if 'annual_revenue' not in record:
 
         if 'annual_revenue' not in record:
             raise ValueError('Missing field annual revenue');
+
             raise ValueError('Missing field annual revenue')
 
         if record.annual_revenue <= 0:
 
         if record.annual_revenue <= 0:
             raise ValueError('Annual Revenue must be > 0');
+
             raise ValueError('Annual Revenue must be > 0')
 
</source>
 
</source>

Latest revision as of 15:35, 15 March 2017

This script validates that certain fields are in the POST request when creating records. If not, an exception is thrown and 500 error returned to the client. If the script exits normally with no exception being thrown, then the records will be written to the database and the post-process script, if any, will be run.

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

# POST /api/v2/db/_table/account triggers script db._table.account.post.pre_process
# This script runs BEFORE records are written to the db.
 
payload = event.request.payload
 
if(payload.resource):
    for record in payload.resource:
        if 'annual_revenue' not in record:
            raise ValueError('Missing field annual revenue')
        if record.annual_revenue <= 0:
            raise ValueError('Annual Revenue must be > 0')