Action with output_schema validation and a return with a datetime object

Here i will post an example because i was falling over it

I defined a simple action with returns a dict and a datetime object in it

Follow error i always recieve:

error: "u"{'values': [{'datestr': datetime.datetime(2020, 4, 14, 13, 51, 9, 13208), 'test1': 'test1', 'test2': 1}]}" is not of type 'object'

Resolution:
ST2 always need a serialize able return object!! and datetime object is not serializeable!

test.yaml

---
runner_type: python-script
entry_point: test.py
name: test
pack: smbutils
output_schema:
  values:
    type: array
    items:
      test1:
        type: string
      test2:
        type: number
      datestr: 
        type: string

test.py

from st2common.runners.base_action import Action
from datetime import datetime
import json

class cleanup(Action):
  def run(self):

    output={ 'values': [ { 'test1': 'test1', 'test2': 1, 'datestr': datetime.utcnow() } ] }

    # Datetime is not serializeable this is wy it is not working
    # we serialize result with a json encoder and then deserialze it again(lol)
    json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime) else None)
    json_object = json.dumps(output)
    serializeable_object = json.loads(json_object)
    return (True, serializeable_object)
1 Like