A Python web framework that makes the most of the filesystem.
Simplates are the main attraction.

JSON Helpers

Aspen ships with a json_dump renderer that will Python-eval the contents of the template section and then call json.dumps on it.


Make a greetings.json.spt file with this content:

import random
n = random.choice(range(10))
extra_excitement = "!" * n
[---] via json_dumps
{'Greetings': 'program!' + extra_excitement}

Now hit this in your browser:

The aspen.json Library

Aspen’s json_dump renderer does not use the standard library's json module. Rather, it uses an extended version of it from aspen.json. The purpose of this extension is twofold:

  1. to delegate to simplejson if available
  2. to provide nicer encoder configuration

Supported Implementations

Aspen's aspen.json library will prefer simplejson if it is available, falling back to the standard library’s json module, which was added in Python 2.6. The latter is a more or less out-of-date version of the former. It also doesn’t have any C speedups. If Aspen can’t find either, then attempts to use the json_dump renderer will raise an ImportError.

Default Encoders

Aspen's aspen.json will serialize instances of the following types. Instances of any other type will raise TypeError, so be sure to pre-process your output if it contains anything else.

Custom Encoders

It’s fairly common to want to add encoders for custom classes or classes otherwise unknown to one or another version of simplejson. To this end, Aspen provides an API to manage a registry of encoders. These functions can be imported from aspen.json:

def register_encoder(cls, encode):
    """Register the encode function for cls.

    An encoder should take an instance of cls and return something
    basically serializable (strings, lists, dictionaries).


def unregister_encoder(cls):
    """Given a class, remove any encoder that has been registered for it.

These functions don’t affect the underlying simplejson library, only the Aspen abstraction layer. So if for example you have a simplejson that knows about Decimal objects (support for which was added in version 2.1 of the library), then if you register a custom encoder for Decimals, Aspen will use that where appropriate, and if you unregister it, the underlying implementation will be used again. Furthermore, if you use the simplejson library directly, the encoders registered with aspen.json won’t be used at all.