Data type configuration for Py3o

Introduction

This module implements new, configurable data types that are intended to be used along with Py3o templates.

These data types should be used in the data source dictionary, as a replacement to builtin (int, float...) and standard (date, time...) types. Their rendering is based on a configuration that can be saved and loaded as custom properties inside a ODF file.

Define the configuration in a ODF file

Configuration keys can be defined directly inside the template, to be loaded by the rendering application.

The custom properties can be set in File > Properties > Custom Properties:

_images/custom_properties.png

Use the configuration in Python code

The configuration is represented by a Py3oTypeConfig instance. This object can be created by extracting the custom properties from a ODT file, using the class method Py3oTypeConfig.from_odf_file(). An optional defaut argument can be specified to provide default values for configuration keys that are not already present in the template:

readable_odf_file = open('template.odt', 'rb')
default = {'digit_separator': u"\u00A0"}
config = Py3oTypeConfig.from_odf_file(readable_odf_file, default=default)

It is also possible to use the constructor to define a configuration directly:

config = Py3oTypeConfig(date_format='%d/%m/%y')

The generated, configured data types can then be accessed as attributes of the configuration instance:

data_dict = {
    'invoice_date': config.date.strptime('2016-04-20', '%Y-%m-%d'),
    'amount': config.float(430.27),
}

Apply the configuration to a ODF file

Conversely, the configuration parameters can be stored in a ODF file for later extraction by calling the method Py3oTypeConfig.apply_to_odf_file(). This method returns a file-like object that contains a copy of the initial ODF file, with the metadata that corresponds to the configuration instance:

default_configured_template = config.apply_to_odf_file(readable_odf_file)
requests.post(url, template=default_configurated_template, data=data_dict)

A configuration instance can also be applied to another ODF file:

origin_odf_file = open('other_template.odt', 'rb')
new_odf_file = open('configured_other_template.odt', 'wb')
config.apply_to_odf_file(origin_odf_file, out_file=new_odf_file)