API

objson

Used to deserialize and serialize json

objson.load(src, *args, **kwargs)

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object.

If the contents of fp is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with codecs.getreader(fp)(encoding), or simply decoded to a unicode object and passed to loads()

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

objson.loads(src, *args, **kwargs)

Deserialize s (a str or unicode instance containing a JSON document) to a Python object.

If s is a str instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to unicode first.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

objson.dump(obj, fp, *args, **kwargs)

Serialize a object to a file object.

Basic Usage:

>>> import simplekit.objson
>>> from cStringIO import StringIO
>>> obj = {'name': 'wendy'}
>>> io = StringIO()
>>> simplekit.objson.dump(obj, io)
>>> print io.getvalue()
Parameters:
  • obj – a object which need to dump
  • fp – a instance of file object
  • args – Optional arguments that json.dump() takes.
  • kwargs – Keys arguments that json.dump() takes.
Returns:

None

objson.dumps(obj, *args, **kwargs)

Serialize a object to string

Basic Usage:

>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
Parameters:
  • obj – a object which need to dump
  • args – Optional arguments that json.dumps() takes.
  • kwargs – Keys arguments that json.dumps() takes.
Returns:

string

objson.make_dynamic_class(typename, field_names)

a factory function to create type dynamically

The factory function is used by objson.load() and objson.loads(). Creating the object deserialize from json string. The inspiration come from collections.namedtuple(). the difference is that I don’t your the class template to define a dynamic class, instead of, I use the type() factory function.

Class prototype definition

class JsonObject(object):
    __identifier__ = "dolphin"

    def __init__(self, kv=None):
        if kv is None:
            kv = dict()
        self.__dict__.update(kv)

    def __getitem__(self, key):
        return self.__dict__.get(key)

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __iter__(self):
        return iter(self.__dict__)

    def __repr__(self):
        keys = sorted(self.__dict__.keys())
        text = ', '.join(["%s=%r" % (key, self[key]) for key in keys])
        return '{%s}' % text

    name=_property('name')

Basic Usage

from objson import make_dynamic_class, dumps
Entity = make_dynamic_class('Entity', 'name, sex, age')
entity = Entity()
entity.name, entity.sex, entity.age = 'benjamin', 'male', 21
dumps(entity)
Parameters:
  • typename – dynamic class’s name
  • field_names – a string list and a field name string which separated by comma, ['name', 'sex'] or "name,sex"
Returns:

a class type

config

class config.SQLiteConfig(db_full_path, default=None, logger=None)

Configuration with SQLite file

Provide retrieve, update, and delete (key, value) pair style configuration. Any changed will save to SQLite file.

Basic Usage::
>>> import simplekit.config
>>> config = simplekit.config.SQLiteConfig('configuration.db', default=dict(name='benjamin'))
>>> assert config.name == 'benjamin'
>>> config.age = 21
>>> config['high'] = 175
>>> config.close()
>>> config = simplekit.config.SQLiteConfig('configuration.db')
>>> assert config.name == 'benjamin'
>>> assert config.age == 21
>>> assert config['age'] == 21
>>> assert config.high == 175
>>> assert config['high'] == 175
>>> del config.age
>>> del config['high']
>>> assert config.age is None
>>> assert config.high is None
>>> config.generic_name = 'benjamin'
>>> config.generic_age = 27
>>> config.generic_high = 175
>>> groups = config.get_namespace('generic_')
>>> assert groups == dict(name='benjamin', age=27, high=175)
get_namespace(namespace, lowercase=True, trim_namespace=True)

Returns a dictionary containing a subset of configuration options

that match the specified namespace/prefix. Example usage::
app.config[‘IMAGE_STORE_TYPE’]=’fs’ app.config[‘IMAGE_STORE_PATH’]=’/var/app/images’ app.config[‘IMAGE_STORE_BASE_URL’]=’http://img.website.com
The result dictionary image_store would look like::
{ ‘type’: ‘fs’, ‘path’: ‘/var/app/images’, ‘base_url’:’http://image.website.com‘ }

This is often useful when configuration options map directly to keyword arguments in functions or class constructors.

Parameters:
  • namespace – a configuration namespace
  • lowercase – a flag indicating if the keys of the resulting dictionary should be lowercase
  • trim_namespace – a flag indicating if the keys of the resulting dictionary should not include the namespace
Returns:

a dict instance

config.import_string(import_name, silent=False)

Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (xml.sax.saxutils.escape) or with a colon as object delimiter (xml.sax.saxutils:escape).

If silent is True the return value will be None if the import fails.

Parameters:
  • import_name – the dotted name for the object to import.
  • silent – if set to True import errors are ignored and None is returned instead.
Returns:

imported object