Storing anvil.server.context.client in data table

I’ve just been picking away at this throughout the day as I’m working and here is what I have so far:

def serialize_nested(obj):
  #  Used to recursively extend easily serializable types that
  #  Would normally raise a SerializationError exception
  if hasattr(obj, '__iter__' ) or hasattr(obj, '__next__'):
    if isinstance(obj, (str, anvil._server.LiveObjectProxy) ):
      return obj
    if isinstance(obj, dict):
      for k in obj:
        obj[k] = serialize_nested(obj[k])
    elif hasattr(obj, '__dict__'):
      obj = dict(obj.__dict__)
      for k in obj:
        obj[k] = serialize_nested(obj[k])
    else:
      obj = list(obj)
      for i, o in enumerate(obj):
        obj[i] = serialize_nested(o)
        
  elif hasattr(obj, '__dict__'):
    obj = dict(obj.__dict__)
    for k in obj:
      obj[k] = serialize_nested(obj[k])
          
  if isinstance(obj, # serializable types that are not portable classes 
                       (   str, int, float,
                       list, bool, dict, datetime.date,
                       datetime.datetime, anvil.Media, 
                       anvil._server.LiveObjectProxy, ) 
                           ) or obj is None :
    return obj

  if hasattr(obj, '__str__') or hasattr(obj, '__repr__'):
    return str(obj)
  
  raise anvil.server.SerializationError(f'Cannot serialize {type(obj)}')
  


It should be extendable, but if you need more power than this you are probably already using portable classes which should already be serializable.

2 Likes