API reference

Module dja_skel.lib.skeleton

This module defines a class that models an skeleton.

An skeleton is a directory containing some templates and static files plus some intelligence that can perform tasks programmatically. An skeleton is defined by sub-classing the dja_skel.lib.skeleton.Skeleton class or one of its subclasses (see dja_skel.skeletons):

class MySkeleton(Skeleton):
    variables = ("prjname", "version")
    skeleton_path = "templates/my_skeleton"
    name = "my_skeleton"

    def frobnicate(self):
        # this method performs some task on the
        # result of instantiating the skeleton
        pass

The instantiation of an skeleton is the process of rendering the individual templates (performing variable substitution and so on), copying the static files and executing the logic that fine tunes the final result. In order to instantiate an skeleton a destination directory and a dictionary mapping template variable names to their actual value are required.

skel = MySkeleton()
skel.instantiate("/path/to/some/dir", { "var" : "value" })

Any file within the skeleton_path directory whose name ends with the _tmpl suffix is considered a template that must be rendered. All other files will be copied verbatim.

File and directory names can be parameterised too, just enclose the variable parts within braces and they will be expanded upon skeleton instantiation. For example, if the skeleton directory contains a file named {var}.py the previous instantiation will create a file value.py.

An skeleton may be build upon other skeletons, such skeleton is named a compound skeleton.

class MySkeleton(Skeleton):
    skeleton_path = "templates/my_skeleton"
    name = "my_skeleton"
    base_skeletons = (AnSkeleton, OtherSkeleton)

When a compound skeleton is instantiated in the first place the base skeletons are instantiated, in reverse order of declaration, and then the parent skeleton is instantiated. This way it’s clear what files prevail in case of conflict. That functionality makes easy building complex skeletons based on simpler ones or overriding some parts of an existing skeleton. In order to avoid variable clashes when instantiating a compound skeleton every participant will receive a shallow copy of the context dictionary, that way they can modify the context as required without interferences.

The skeleton machinery does not force you to use a particular template engine, instead it uses a pluggable architecture that eases using whatever template engine you feel more comfortable with. See dja_skel.lib.templating.Engine.

The Skeleton class

class dja_skel.lib.skeleton.Skeleton

This class models an skeleton and provides a method for instantiating it.

Warning

Instances of this class are not thread safe although they can be safely reused after instantiation is finished.

It defines the following class attributes:

base_skeletons = ()

list of skeleton classes this one is based upon.

skeleton_path

path to the directory where templates and static files are stored. It must be a relative path. It is first looked for in the directory containing the module that defines the skeleton, then in its parent until it’s found or the root of the package is reached.

name

name of the skeleton.

variables = ()

an iterable of strings declaring variables required by the skeleton. This parameter is used for documentation purposes.

template_engine = "format"

name of the template engine used to render the templates. By default the string method format is used. The value is looked up in the entry points defined in the group dja_skel.template_engine. The first match is used.

template_engine_parametres = {}

a dictionary whose values will be passed as keyword arguments to the template engine constructor. Default an empty dict.

When an skeleton is instantiated the following steps are executed:

  1. the before_instantiation() method is called. This is a good place to place initialisation code and the like.
  2. the get_extra_context() method is called. This method is responsible for gathering extra context variables.
  3. the actual instantiation is performed
  4. the after_instantiation() method is called. This is a good place to perform tasks that further customise the result of the instantiation.

Subclasses may override the methods before_instantiation(), after_instantiation() and get_extra_context(). Don’t forget to call super in order to play nicely with base classes.

__init__()

Constructor.

It is required that the constructor on subclasses accepts no parameters.

after_instantiation()

Performs post instantiation tasks.

This method is called after the skeleton has been instantiated.

before_instantiation(dest_dir, context, encoding)

Performs initial setup tasks.

This method is called before skeleton instantiation. It receives the same parameters that instantiate().

get_extra_context(context)

Gather extra context.

This method is called before skeleton instatiation in order to gather extra context. It defines the variables:

Skel_environ :the value of os.environ
Skel_root_path :
 the path to the destination directory passed to instantiate().
Skel_encoding :the encoding passed to instantiate().

Classes overriding this method can add variables to the context dictionary as required. Care must be taken in order to avoid name clashes. Variable names starting with the skel_ prefix are reserved.

Parameters:context – a dictionary mapping variable names to values.
Returns:the context dictionary.
Return type:dict
instantiate(dest_dir, context, encoding='utf-8')

Instantiate the skeleton.

This method is the public entry point for the class.

Parameters:
  • dest_dir – the path of the directory where the result will be saved. It’s not required but is advisable to use an absolute path.
  • context – a dictionary mapping variable names to values. It will be used for variable substitution in templates and file names. Internally this class works with unicode strings, so it is expected that the string values are stored in the context as unicode strings.
  • encoding – the desired encoding for the output files. It is only meaningful for templates, the static files are copied verbatim.

Package dja_skel.skeletons

The dja_skel.skeletons package defines some skeleton classes.

Module dja_skel.skeletons.base

This module defines some base skeletons.

class dja_skel.skeletons.base.BaseAppSkel

Base class for skeletons that operate on an existing django app.

Attributes:

class dja_skel.skeletons.base.BaseDjangoSkel

Base class for skeletons related to django.

Context:

  • django_version: a tuple that stores the django version. For example (1, 4, 1)
class dja_skel.skeletons.base.BaseModelSkel

Base class for skeleton that operate on a django model.

Attributes:

  • model_name: name of the model
  • model: model class, it may be None if the model does not exits (we are creating it).

Context:

  • model_name: uncamelized and underscorized version of the model name. For example my_model.
  • Model_name: capitalized and whitespaced version of the model name. For example My model.
  • modelname: lowercased version of the model name. For example mymodel.
  • model: a dja_skel.lib.model_introspection.ModelIntrospector instance.
class dja_skel.skeletons.base.BaseModelViewSkel

Base class for skeletons that generate a view somewhat related to a model.

It inherits from BaseModelSkel and ViewSkelMixin and overrides the after_instantiation() method in order to call the ViewSkelMixin.add_view_imports() and ViewSkelMixin.add_view_urls() methods.

class dja_skel.skeletons.base.BaseProjectSkel

Base class for skeletons that operate on a django project.

Attributes:

class dja_skel.skeletons.base.BaseViewSkel

Base class for skeletons that generate a view.

It inherits from BaseAppSkel and ViewSkelMixin and overrides the after_instantiation() method in order to call the ViewSkelMixin.add_view_imports() and ViewSkelMixin.add_view_urls() methods.

class dja_skel.skeletons.base.ViewSkelMixin

This mixin provides common funcionality useful for skeletons that generate views.

Usually classes using this mixin will override the get_view_module_map() and get_view_url_map() methods and call the add_view_imports() and add_view_urls() methods from the post_instantiation() method.

Markers:

  • views/__init__.py: -*- VIEW IMPORTS -*-
  • urls.py: -*- VIEW URLS -*-
add_view_imports()

This method gathers information about the created views (by calling get_view_module_map()) and inserts the appropriate imports into the views/__init__.py module.

add_view_urls()

This method gathers information about the created views (by calling get_view_url_map()) and inserts the appropriate url patterns into the urls.py module.

get_view_module_map()

Returns a list of pairs (module, view), where view is the name of a view created by the skeleton and module is the name of the module where the view has been created. Subclasses must override this method.

If this method returns [("mymodule", "myview")] the mixin will insert from <applabel>.views.mymodule import myview into the views/__init__.py module before the -*- VIEW IMPORTS -*- marker.

get_view_url_map()

Returns a list of pairs (url, view), where view is the name of a view created by the skeleton and url is the URL pattern for that view.

I this method returns [("myurlpattern", "myview")] the mixin will insert url(r"myurlpattern", views.myview, name='myview'), into the urls.py module.

Module dja_skel.skeletons.app

Module dja_skel.skeletons.crud

Module dja_skel.skeletons.list

Module dja_skel.skeletons.model

Module dja_skel.skeletons.project

Module dja_skel.skeletons.update

class dja_skel.skeletons.update.UpdateViewSkel

Skeleton for the update view.

Module dja_skel.lib.templating

Every template engine has its own API. An adapter API is defined in order to isolate the skeleton machinery from the actual template engine being used to render the template.

Skeletons expect that the engine adapter classes define two methods:

  • __init__(input_encoding=’utf-8’, **kwargs)

    The engine adapter constructor must accept only keyword arguments. At this point only one argument is defined:

    param input_encoding:
     encoding used in the template.
  • render(path, context)

    Renders the template given by the path path using the variables defined in context. The template is expected to be encoded in the input_encoding encoding.

    param path:path of the template
    param context:dictionary mapping variables to values.
    returns:the rendered template
    rtype:an unicode string

The template engine adapter must take care of adapting exceptions raised by the template engine. At this point two translations are defined:

In order to create an adapter a class implementing the API must be defined and registered under the dja_skel.template_engine entry point.

The Engine base class

class dja_skel.lib.templating.Engine(**kw)

This class implements the adapter API. Template engine adapters are not required to inherit from this class. It just provides some common functionality to ease the creation of new adapters.

Subclasses must override the _render() method.

__init__(**kw)

Stores the arguments in the opts attribute (an object).

render(path, context)

Render the template.

This implementation reads the template from the filesystem, decodes it using the input_encoding argument specified in the constructor and finally calls the _render() method.

_render(template, context, path)

Actual renderer.

Called by render(). It receives the template as an unicode string and must return the result as unicode.

Parameters:
  • template – unicode string with template contents.
  • context – dictionary mapping variables to values.
  • path – path of the template, mostly useful to report errors.
Returns:

the rendered template.

Return type:

an unicode string.

Module dja_skel.lib.errors

exception dja_skel.lib.errors.SkelError

Base exception.

exception dja_skel.lib.errors.TemplateError(message, filename)

Exception raised when an error is encountered in a template.

The exception object has the following attributes:

filename

path of the template that raised the exception.

message

error message provided by the template engine.

exception dja_skel.lib.errors.UndefinedVarError(varname, filename)

Exception raised whenever a variable required by a template is missing from the context dictionary.

The exception object has the following attributes:

filename

path of the template that raised the exception.

varname

name of the offending variable.

Helper classes

Module dja_skel.lib.python_package

This modules provides some convenience classes to ease the management of python packages.

In that context a package is a directory with and __init__.py while a module is any file.py.

class dja_skel.lib.python_package.DjangoApp(appname)

Django app

class dja_skel.lib.python_package.DjangoProject

Django project

class dja_skel.lib.python_package.PythonPackage(path=None, pkg=None)

Python package.

get_file(rel_path, encoding='utf-8')
is_dir(rel_path)

Cheks if rel_path points to a directory.

Parameters:rel_path
Raises :
Returns:True if rel_path is a directory, False otherwise.
Return type:bool
is_file(rel_path)

Checks if rel_path points to a file.

Parameters:rel_path
Raises :
Returns:True if rel_path is a file, False otherwise.
Return type:bool
is_module(dot_path)

Checks if dot_path points to a module.

Parameters:dot_path
Raises :
Returns:True if dot_path is a module, False otherwise
Return type:bool
is_package(dot_path)

Checks if dot_path points to a package.

Parameters:dot_path
Raises :
Returns:True if dot_path is a package, False otherwise.
Return type:bool

Module dja_skel.lib.model_introspection

class dja_skel.lib.model_introspection.ModelIntrospector(model)