morepath.traject – Routing

Implementation of routing.

The idea is to turn the routes into a tree, so that the routes:


become a tree like this:


Nodes in the tree can have a value attached that can be found through routing; in Morepath the value is a model instance factory.

When presented with a path, Traject traverses this internal tree.

For a description of a similar algorithm also read:

class morepath.traject.Node

A node in the traject tree.


Add a step into the tree as a child node of this node.


Add a step into the tree as a node that doesn’t match variables.


Add a step into the tree as a node that matches variables.

resolve(segment, variables)

Match a path segment, traversing this node.

Matches non-variable nodes before nodes with variables in them.

Updates the variables argument.

Segment:a path segment
Variables:variables dictionary to update.
Returns:matched node, or None if node didn’t match.
class morepath.traject.ParameterFactory(parameters, converters, required, extra=False)

Convert URL parameters.

Given expected URL parameters, converters for them and required parameters, create a dictionary of converted URL parameters with Python values.

  • parameters – dictionary of parameter names -> default values.
  • converters – dictionary of parameter names -> converters.
  • required – dictionary of parameter names -> required booleans.
  • extra – should extra unknown parameters be included?

Convert URL parameters to Python dictionary with values.

class morepath.traject.Path(path)

Helper when registering paths.

Used by morepath.App.path() to register inverse paths used for link generation.

Also used by morepath.App.path() for creating discriminators.

Parameters:path – the route.

Creates a unique discriminator for the path.


Create a string for interpolating variables.

Used for link generation (inverse).


Get the variables used by the path.

Returns:a list of variable names
class morepath.traject.Step(s, converters=None)

A single step in the tree.

  • s – the path segment, such as 'foo' or '{variable}' or 'foo{variable}bar'.
  • converters – dict of converters for variables.

True if this step is the same as another.


x.__ge__(y) <==> x>=y


x.__gt__(y) <==> x>y


x.__le__(y) <==> x<=y


Used for inserting steps in correct place in the tree.

The order in which a step is inserted into the tree compared to its siblings affects which step preferentially matches first.

In Traject, steps that contain no variables match before steps that do contain variables. Steps with more specific variables sort before steps with more general ones, i.e. prefix{foo} sorts before {foo} as prefix{foo} is more specific.


True if this step is not equal to another.


Information needed to construct path discriminator.


True if there are any variables in this step.

match(s, variables)

Match this step with actual path segment.

  • s – path segment to match with
  • variables – variables dictionary to update with new converted variables that are found in this segment.

bool. The bool indicates whether s matched with the step or not.


Validate whether step makes sense.

Raises morepath.error.TrajectError if there is a problem with the segment.


Check whether all non-variable parts of the segment are valid.

Raises morepath.error.TrajectError if there is a problem with the segment.


Check whether all variables of the segment are valid.

Raises morepath.error.TrajectError if there is a problem with the variables.

class morepath.traject.StepNode(step)

A node that is also a step in that it can match.

Parameters:step – the step
match(segment, variables)

Match a segment with the step.

class morepath.traject.TrajectRegistry

Tree of route steps.

add_pattern(path, model_factory, defaults=None, converters=None, absorb=False, required=None, extra=None, code_info=None)

Add a route to the tree.

  • path – route to add.
  • model_factory – the factory used to construct the model instance
  • defaults – mapping of URL parameters to default value for parameter
  • converters – converters to store with the end step of the route
  • absorb – does this path absorb all segments
  • required – list or set of required URL parameters
  • extra – bool indicating whether extra parameters are expected
  • code_infodectate.CodeInfo instance describing the code line that registered this path.

Consume a stack given route, returning object.

Removes the successfully consumed path segments from morepath.Request.unconsumed.

Extracts variables from the path and URL parameters from the request.

Then constructs the model instance given this information. (or morepath.App instance in case of mounted apps).

Parameters:request – the request to consume segments from and to retrieve URL parameters from.
Returns:the model instance that can be found, or None if no model instance exists for this sequence of segments.

Builds a path from a list of segments.

Parameters:stack – a list of segments
Returns:a path

Create regular expression that matches variables from route segment.

Parameters:s – a route segment with variables in it.
Returns:a regular expression that matches with variables for the route.

Generalize a route segment.

Parameters:s – a route segment.
Returns:a generalized route where all variables are empty ({}).

Create a Python string with interpolation variables for a route segment.

Given a{foo}b, creates a%sb.


Check whether a variable name is a proper identifier.

Parameters:s – variable
Returns:True if variable is an identifier.

Converts path into normalized path.


  • Collapse dots:

    >>> normalize_path('/../blog')
  • Ensure absolute paths:

    >>> normalize_path('./site')
  • Remove double-slashes:

    >>> normalize_path('//index')

For example:

>>> normalize_path('../static//../')
Parameters:path – path string to parse
Returns:normalized path.

Parses path, creates normalized segment list.

Dots are collapsed:

>>> parse_path('../static//../')
Parameters:path – path string to parse
Returns:normalized list of path segments.

Parse variables out of a segment.

Raised a morepath.error.TrajectError if a variable is not a valid identifier.

Parameters:s – a path segment
Returns:a list of variables.
morepath.traject.IDENTIFIER = <_sre.SRE_Pattern object>

regex for a valid variable name in a route.

same rule as for Python identifiers.

morepath.traject.PATH_VARIABLE = <_sre.SRE_Pattern object>

regex to find curly-brace marked variables {foo} in routes.