The userhooks parameter allows you to pass a list of hooks to be used during serialization. This is simply a list of functions as defined below. Whenever boodebr.ion is unable to serialize an object, the object is passed to the hooks to see if any of them want to handle it. If so, the hook should convert it to a serializable type.
Hooks are called as:
(handled, name, obj) = hook(obj)
Where:
handled:
True/False if hook handled/modified obj.
name:
Name of this hook (used during deionization). Can be None if you don't need a deionization hook to be called.
Only used if handled==True
obj:
The modified object.
Can by any Python object, but dicts are most useful since you can cause a hook to be called during deserialization (i.e. to recreate the original object).
Only used if handled==True
Any hooks you pass will be called before the builtin hooks, so that you can override any builtin behavior you want to.
boodebr.ion's builtin hooks are located in the package boodebr.ion.hooks, if you want to use them as a reference.
deionization
The deionize() API is:
obj = deionize(buf, userhooks=None)
The userhooks parameter is a dictionary mapping names to hook functions. The names are the names returned by the ionization hooks. For example, if your ionization hook returned name='MyHook', then you would pass userhooks={'MyHook': my_deionize_hook}. As with ionize, any hooks you pass will override the builtin hooks.
Hooks are called as:
obj = hook(mod_obj)
Where:
mod_obj
The object that the ionization hook returned.
Returns the (presumably) recreated object.
Brief example
A brief example to demonstrate.
Here is a generic pair of hooks:
from boodebr.ion.hooks import ignore
def ionize_hook(obj): ... decide if I want to handle 'obj' ... if dont_want_object(obj): return ignore()
... turn obj into mod_obj ...
return (True, 'MyHookName', mod_obj)
def deionize_hook(mod_obj):
... do work to recreate original obj from mod_obj ...
return obj
To use the hooks you would do:
s = ionize(obj, userhooks=[ionize_hook]) obj = deionize(s, userhooks={'MyHookName': deionize_hook})
Adding __ionize__()
If you simply want to flatten your data, i.e. for sending to a JSON client, you can avoid writing a full-blown hook by adding an __ionize__() function to your objects.
A simple example:
class ObjA(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c
def __ionize__(self): # flatten myself to a dict (can be any object) return {'A': self.a, 'B': self.b, 'C': self.c}
from boodebr.ion import ionize print "Result" print ionize(ObjA(1,'222', 33.333))