Morepath API

class morepath.App

A Morepath-based application object.

You subclass App to create a morepath application class. You can then configure this class using Morepath decorator directives.

An application can extend one or more other applications, if desired, by subclassing them. By subclassing App itself, you get the base configuration of the Morepath framework itself.

Conflicting configuration within an app is automatically rejected. An subclass app cannot conflict with the apps it is subclassing however; instead configuration is overridden.

You can turn your app class into a WSGI application by instantiating it. You can then call it with the environ and start_response arguments.

request_class

The class of the Request to create. Must be a subclass of morepath.Request.

alias of Request

@converter(type)

Register custom converter for type.

Parameters:type – the Python type for which to register the converter. Morepath uses converters when converting path variables and URL parameters when decoding or encoding URLs. Morepath looks up the converter using the type. The type is either given explicitly as the value in the converters dictionary in the morepath.App.path() directive, or is deduced from the value of the default argument of the decorated model function or class using type().

Defer link generation for model to mounted app.

With defer_links you can specify that link generation for instances of model is to be handled by a returned mounted app it cannot be handled by the given app itself. Request.link() and Request.view() are affected by this directive.

The decorated function gets an instance of the application and object to link to. It should return another application that it knows can create links for this object. The function uses navigation methods on App to do so like App.parent() and App.child().

Parameters:model – the class for which we want to defer linking.
@dump_json(model=<type 'object'>)

Register a function that converts model to JSON.

The decorated function gets self (model instance) and request (morepath.Request) parameters. The function should return an JSON object. That is, a Python object that can be dumped to a JSON string using json.dump.

Parameters:model – the class of the model for which this function is registered. The self passed into the function is an instance of the model (or of a subclass). By default the model is object, meaning we register a function for all model classes.
@function(func, **kw)

Register function as implementation of generic dispatch function

The decorated function is an implementation of the generic function supplied to the decorator. This way you can override parts of the Morepath framework, or create new hookable functions of your own.

The func argument is a generic dispatch function, so a Python function marked with app.dispatch() or app.predicate_dispatch().

Parameters:
  • func (dispatch function object) – the generic function to register an implementation for.
  • kw – keyword parameters with the predicate keys to register for. Argument names are predicate names, values are the predicate values to match on.
@html(model, render=None, template=None, permission=None, internal=False, **predicates)

Register HTML view.

This is like morepath.App.view(), but with morepath.render_html() as default for the render function.

Sets the content type to text/html.

Parameters:
  • model – the class of the model for which this view is registered.
  • name – the name of the view as it appears in the URL. If omitted, it is the empty string, meaning the default view for the model.
  • render – an optional function that can render the output of the view function to a response, and possibly set headers such as Content-Type, etc. Renders as HTML by default. This function takes self and request parameters as input.
  • template

    a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.

    Use the morepath.App.template_engine() directive to define support for new template engines.

  • permission – a permission class. The model should have this permission, otherwise access to this view is forbidden. If omitted, the view function is public.
  • internal – Whether this view is internal only. If True, the view is only useful programmatically using morepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view is False, so not internal.
  • name – the name of the view as it appears in the URL. If omitted, it is the empty string, meaning the default view for the model. This is a predicate.
  • request_method – the request method to which this view should answer, i.e. GET, POST, etc. If omitted, this view will respond to GET requests only. This is a predicate.
  • predicates – predicates to match this view on. See the documentation of App.view() for more information.
@identity_policy

Register identity policy.

The decorated function should return an instance of morepath.security.IdentityPolicy. Either use an identity policy provided by a library or implement your own.

It gets one optional argument: the settings of the app for which this identity policy is in use. So you can pass some settings directly to the IdentityPolicy class.

@json(model, render=None, template=None, permission=None, internal=False, **predicates)

Register JSON view.

This is like morepath.App.view(), but with morepath.render_json() as default for the render function.

Transforms the view output to JSON and sets the content type to application/json.

Parameters:
  • model – the class of the model for which this view is registered.
  • name – the name of the view as it appears in the URL. If omitted, it is the empty string, meaning the default view for the model.
  • render – an optional function that can render the output of the view function to a response, and possibly set headers such as Content-Type, etc. Renders as JSON by default. This function takes self and request parameters as input.
  • template

    a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.

    Use the morepath.App.template_engine() directive to define support for new template engines.

  • permission – a permission class. The model should have this permission, otherwise access to this view is forbidden. If omitted, the view function is public.
  • internal – Whether this view is internal only. If True, the view is only useful programmatically using morepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view is False, so not internal.
  • name – the name of the view as it appears in the URL. If omitted, it is the empty string, meaning the default view for the model. This is a predicate.
  • request_method – the request method to which this view should answer, i.e. GET, POST, etc. If omitted, this view will respond to GET requests only. This is a predicate.
  • predicates – predicates to match this view on. See the documentation of App.view() for more information.

Register a function that returns the prefix added to every link generated by the request.

By default the link generated is based on webob.Request.application_url().

The decorated function gets the request (morepath.Request) as its only paremeter. The function should return a string.

@load_json

Register a function that converts JSON to an object.

The decorated function gets json and request (morepath.Request) parameters. The function should return a Python object based on the given JSON.

@mount(path, app, variables=None, converters=None, required=None, get_converters=None, name=None)

Mount sub application on path.

The decorated function gets the variables specified in path as parameters. It should return a new instance of an application class.

Parameters:
  • path – the path to mount the application on.
  • app – the morepath.App subclass to mount.
  • variables – a function that given an app instance can construct the variables used in the path (including any URL parameters). If omitted, variables are retrieved from the app by using the arguments of the decorated function.
  • converters – converters as for the morepath.App.path() directive.
  • required – list or set of names of those URL parameters which should be required, i.e. if missing a 400 Bad Request response is given. Any default value is ignored. Has no effect on path variables. Optional.
  • get_converters – a function that returns a converter dictionary. This function is called once during configuration time. It can be used to programmatically supply converters. It is merged with the converters dictionary, if supplied. Optional.
  • name – name of the mount. This name can be used with Request.child() to allow loose coupling between mounting application and mounted application. Optional, and if not supplied the path argument is taken as the name.
@path(path, model=None, variables=None, converters=None, required=None, get_converters=None, absorb=False)

Register a model for a path.

Decorate a function or a class (constructor). The function should return an instance of the model class, for instance by querying it from the database, or None if the model does not exist.

The decorated function gets as arguments any variables specified in the path as well as URL parameters.

If you declare a request parameter the function is able to use that information too.

Parameters:
  • path – the route for which the model is registered.
  • model – the class of the model that the decorated function should return. If the directive is used on a class instead of a function, the model should not be provided.
  • variables – a function that given a model object can construct the variables used in the path (including any URL parameters). If omitted, variables are retrieved from the model by using the arguments of the decorated function.
  • converters – a dictionary containing converters for variables. The key is the variable name, the value is a morepath.Converter instance.
  • required – list or set of names of those URL parameters which should be required, i.e. if missing a 400 Bad Request response is given. Any default value is ignored. Has no effect on path variables. Optional.
  • get_converters – a function that returns a converter dictionary. This function is called once during configuration time. It can be used to programmatically supply converters. It is merged with the converters dictionary, if supplied. Optional.
  • absorb – If set to True, matches any subpath that matches this path as well. This is passed into the decorated function as the remaining variable.
@permission_rule(model, permission, identity=<class 'morepath.security.Identity'>)

Declare whether a model has a permission.

The decorated function receives model, permission` (instance of any permission object) and identity (morepath.security.Identity) parameters. The decorated function should return True only if the given identity exists and has that permission on the model.

Parameters:
  • model – the model class
  • permission – permission class
  • identity – identity class to check permission for. If None, the identity to check for is the special morepath.security.NO_IDENTITY.
@predicate(dispatch, name, default, index, before=None, after=None)

Register custom predicate for a predicate_dispatch function.

The function registered should have arguments that are the same or a subset of the arguments of the predicate_dispatch function. From these arguments it should determine a predicate value and return it. The predicates for a predicate_dispatch function are ordered by their before and after arguments.

You can then register a function to dispatch to using the App.function() directive. This takes the predicate_dispatch or dispatch function as its first argument and the predicate key to match on as its other arguments.

Parameters:
  • dispatch – the predicate_dispatch function this predicate is for.
  • name – the name of the predicate. This is used when constructing a predicate key from a predicate dictionary.
  • default – the default value for a predicate, in case the value is missing in the predicate dictionary.
  • index – the index to use. Typically morepath.KeyIndex or morepath.ClassIndex.
  • default – the default value for this predicate. This is used as a default value if the argument is ommitted.
  • before – predicate function this function wants to have priority over.
  • after – predicate function we want to have priority over this one.
@predicate_fallback(dispatch, func)

For a given dispatch and function dispatched to, register fallback.

The fallback is called with the same arguments as the dispatch function. It should return a response (or raise an exception that can be turned into a response).

Parameters:
  • dispatch – the dispatch function
  • func – the registered function we are the fallback for
@setting(section, name)

Register application setting.

An application setting is registered under the settings attribute of morepath.app.Registry. It will be executed early in configuration so other configuration directives can depend on the settings being there.

The decorated function returns the setting value when executed.

Parameters:
  • section – the name of the section the setting should go under.
  • name – the name of the setting in its section.
@setting_section(section)

Register application setting in a section.

An application settings are registered under the settings attribute of morepath.app.Registry. It will be executed early in configuration so other configuration directives can depend on the settings being there.

The decorated function returns a dictionary with as keys the setting names and as values the settings.

Parameters:section – the name of the section the setting should go under.
@template_directory(after=None, before=None, name=None)

Register template directory.

The decorated function gets no argument and should return a relative or absolute path to a directory containing templates that can be loaded by this app. If a relative path, it is made absolute from the directory this module is in.

Template directories can be ordered: templates in a directory before another one are found before templates in a directory after it. But you can leave both before and after out: template directories defined in sub-applications automatically have a higher priority than those defined in base applications.

Parameters:
  • after – Template directory function this template directory function to be under. The other template directory has a higher priority. You usually want to use over. Optional.
  • before – Template directory function function this function should have priority over. Optional.
  • name – The name under which to register this template directory, so that it can be overridden by applications that extend this one. If no name is supplied a default name is generated.
@template_loader(extension)

Create a template loader.

The decorated function gets a template_directories argument, which is a list of absolute paths to directories that contain templates. It also gets a settings argument, which is application settings that can be used to configure the loader.

It should return an object that can load the template given the list of template directories.

@template_render(extension)

Register a template engine.

Parameters:extension – the template file extension (.pt, etc) we want this template engine to handle.

The decorated function gets loader, name and original_render arguments. It should return a callable that is a view render function: take a content and request object and return a morepath.Response instance. This render callable should render the return value of the view with the template supplied through its template argument.

@tween_factory(under=None, over=None, name=None)

Register tween factory.

The tween system allows the creation of lightweight middleware for Morepath that is aware of the request and the application.

The decorated function is a tween factory. It should return a tween. It gets two arguments: the app for which this tween is in use, and another tween that this tween can wrap.

A tween is a function that takes a request and a mounted application as arguments.

Tween factories can be set to be over or under each other to control the order in which the produced tweens are wrapped.

Parameters:
  • under – This tween factory produces a tween that wants to be wrapped by the tween produced by the under tween factory. Optional.
  • over – This tween factory produces a tween that wants to wrap the tween produced by the over tween factory. Optional.
  • name – The name under which to register this tween factory, so that it can be overridden by applications that extend this one. If no name is supplied a default name is generated.
@verify_identity(identity=<type 'object'>)

Verify claimed identity.

The decorated function gives a single identity argument which contains the claimed identity. It should return True only if the identity can be verified with the system.

This is particularly useful with identity policies such as basic authentication and cookie-based authentication where the identity information (username/password) is repeatedly sent to the the server and needs to be verified.

For some identity policies (auth tkt, session) this can always return True as the act of establishing the identity means the identity is verified.

The default behavior is to always return False.

Parameters:identity – identity class to verify. Optional.
@view(model, render=None, template=None, permission=None, internal=False, **predicates)

Register a view for a model.

The decorated function gets self (model instance) and request (morepath.Request) parameters. The function should return either a (unicode) string that is the response body, or a morepath.Response object.

If a specific render function is given the output of the function is passed to this first, and the function could return whatever the render parameter expects as input. This function should take the object to render and the request. func:morepath.render_json for instance expects as its first argument a Python object such as a dict that can be serialized to JSON.

See also morepath.App.json() and morepath.App.html().

Parameters:
  • model – the class of the model for which this view is registered. The self passed into the view function is an instance of the model (or of a subclass).
  • render – an optional function that can render the output of the view function to a response, and possibly set headers such as Content-Type, etc. This function takes self and request parameters as input.
  • template

    a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.

    Use the morepath.App.template_loader() and morepath.App.template_render() directives to define support for new template engines.

  • permission – a permission class. The model should have this permission, otherwise access to this view is forbidden. If omitted, the view function is public.
  • internal – Whether this view is internal only. If True, the view is only useful programmatically using morepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view is False, so not internal.
  • name – the name of the view as it appears in the URL. If omitted, it is the empty string, meaning the default view for the model. This is a predicate.
  • request_method – the request method to which this view should answer, i.e. GET, POST, etc. If omitted, this view responds to GET requests only. This is a predicate.
  • predicates – additional predicates to match this view on. You can install your own using the morepath.App.predicate() directive.
ancestors()

Return iterable of all ancestors of this app.

Includes this app itself as the first ancestor, all the way up to the root app in the mount chain.

child(app, **variables)

Get app mounted in this app.

Either give it an instance of the app class as the first parameter, or the app class itself (or name under which it was mounted) as the first parameter and as variables the parameters that go to its mount function.

Returns the mounted application object, with its parent attribute set to this app object, or None if this application cannot be mounted in this one.

classmethod directive(name)

Decorator to register a new directive with this application class.

You use this as a class decorator for a morepath.Directive subclass:

@App.directive('my_directive')
class FooDirective(morepath.Directive):
    ...

This needs to be executed before the directive is being used and thus might introduce import dependency issues unlike normal Morepath configuration, so beware! An easy way to make sure that all directives are installed before you use them is to make sure you define them in the same module as where you define the application class that has them.

request(environ)

Create a Request given WSGI environment for this app.

Parameters:environ – WSGI environment
Returns:morepath.Request instance
sibling(app, **variables)

Get app mounted next to this app.

Either give it an instance of the app class as the first parameter, or the app class itself (or name under which it was mounted) as the first parameter and as variables the parameters that go to its mount function.

Returns the mounted application object, with its parent attribute set to the same parent as this one, or None if such a sibling application does not exist.

lookup

Get the reg.Lookup for this application.

Returns:a reg.Lookup instance.
parent = None

The parent in which this app was mounted.

root

The root application.

morepath.autoconfig(ignore=None)

Automatically load Morepath configuration from packages.

Morepath configuration consists of decorator calls on App instances, i.e. @App.view() and @App.path().

This function tries to load needed Morepath configuration from all packages automatically. This only works if:

  • The package is made available using a setup.py file.
  • The package or a dependency of the package includes morepath in the install_requires list of the setup.py file.
  • The setup.py name is the same as the name of the distributed package or module. For example: if the module inside the package is named myapp the package must be named myapp as well (not my-app or MyApp).

If the setup.py differs from the package name, it’s possible to specify the module morepath should scan using entry points:

setup(name='some-package',
  ...
  install_requires=[
      'setuptools',
      'morepath'
  ],
  entry_points={
      'morepath': [
          'scan = somepackage',
      ]
  })

This function creates a Config object as with setup(), but before returning it scans all packages, looking for those that depend on Morepath directly or indirectly. This includes the package that calls this function. Those packages are then scanned for configuration as with Config.scan().

You can add manual Config.scan() calls yourself on the returned Config object. Finally you need to call Config.commit() on the returned Config object so the configuration is committed.

Typically called immediately after startup just before the application starts serving using WSGI.

autoconfig always ignores .test and .tests sub-packages – these are assumed never to contain useful Morepath configuration and are not scanned.

autoconfig can fail with an ImportError when it tries to scan code that imports an optional dependency that is not installed. This happens most commonly in test code, which often rely on test-only dependencies such as pytest or nose. If those tests are in a .test or .tests sub-package they are automatically ignored, however.

If you have a special package with such expected import errors, you can exclude them from autoconfig using the ignore argument, for instance using ['special_package']. You then can use Config.scan for that package, with a custom ignore argument that excludes the modules that generate import errors.

See also autosetup().

Parameters:ignoreVenusian style ignore to ignore some modules during scanning. Optional. If ommitted, ignore .test and .tests packages by default.
Returns:Config object.
morepath.autosetup(ignore=None)

Automatically commit Morepath configuration from packages.

As with autoconfig(), but also commits configuration. This can be your one-stop function to load all Morepath configuration automatically.

Typically called immediately after startup just before the application starts serving using WSGI.

autosetup always ignores .test and .tests sub-packages – these are assumed never to contain useful Morepath configuration and are not scanned.

autosetup can fail with an ImportError when it tries to scan code that imports an optional dependency that is not installed. This happens most commonly in test code, which often rely on test-only dependencies such as pytest or nose. If those tests are in a .test or .tests sub-package they are automatically ignored, however.

If you have a special package with such expected import errors, you may be better off switching to morepath.autoconfig() with an ignore for this package, and then doing a manual Config.scan for that package with the resulting config object. There you can add a custom ignore argument that excludes the modules that generate import errors.

Parameters:ignoreVenusian style ignore to ignore some modules during scanning. Optional. If ommitted, ignore .test and .tests by default.
morepath.setup()

Set up core Morepath framework configuration.

Returns a Config object; you can then Config.scan() the configuration of other packages you want to load and then Config.commit() it.

See also autoconfig() and autosetup().

Returns:Config object.
morepath.run(wsgi, host=None, port=None)

Uses wsgiref.simple_server to run application for debugging purposes.

Don’t use this in production; use an external WSGI server instead, for instance Apache mod_wsgi, Nginx wsgi, Waitress, Gunicorn.

Parameters:
  • wsgi – WSGI app.
  • host – hostname.
  • port – port.
morepath.settings()

Return current settings object.

In it are sections, and inside of the sections are the setting values. If there is a logging section and a loglevel setting in it, this is how you would access it:

settings().logging.loglevel
morepath.redirect(location)

Return a response object that redirects to location.

class morepath.Request(environ, app, **kw)

Request.

Extends webob.request.BaseRequest

after(func)

Call function with response after this request is done.

You use request.after inside a view function definition.

It can be used explicitly:

@App.view(model=SomeModel)
def some_model_default(self, request):
    def myfunc(response):
        response.headers.add('blah', 'something')
    request.after(my_func)

or as a decorator:

@App.view(model=SomeModel)
def some_model_default(self, request):
    @request.after
    def myfunc(response):
        response.headers.add('blah', 'something')

If the normal response handling is interrupted by an exception either in your own code or by Morepath raising a HTTP exception, then after won’t execute for this exception.

If you directly return a response object from the view, after won’t have any effect either. Instead, you can manipulate the response object directly. Note that this is the case when you use morepath.redirect().

Parameters:func – callable that is called with response
Returns:func argument, not wrapped

Create a link (URL) to a view on a model instance.

The resulting link is prefixed by the link prefix. By default this is the full URL based on the Host header.

You can configure the link prefix for an application using the morepath.App.link_prefix() directive.

If no link can be constructed for the model instance, a :exc:morepath.LinkError is raised. None is treated specially: if None is passed in the default value is returned.

Parameters:
  • obj – the model instance to link to, or None.
  • name – the name of the view to link to. If omitted, the the default view is looked up.
  • default – if None is passed in, the default value is returned. By default this is None.
  • app – If set, change the application to which the link is made. By default the link is made to an object in the current application. The defer_links directive can be used to change the default app for all instances of a particular class (if this app doesn’t handle them).

Prefix to all links created by this request.

resolve_path(path, app=<SAME_APP>)

Resolve a path to a model instance.

The resulting object is a model instance, or None if the path could not be resolved.

Parameters:
  • path – URL path to resolve.
  • app – If set, change the application in which the path is resolved. By default the path is resolved in the current application.
Returns:

instance or None if no path could be resolved.

view(obj, default=None, app=<SAME_APP>, **predicates)

Call view for model instance.

This does not render the view, but calls the appropriate view function and returns its result.

Parameters:
  • obj – the model instance to call the view on.
  • default – default value if view is not found.
  • app – If set, change the application in which to look up the view. By default the view is looked up for the current application. The defer_links directive can be used to change the default app for all instances of a particular class.
  • predicates – extra predicates to modify view lookup, such as name and request_method. The default name is empty, so the default view is looked up, and the default request_method is GET. If you introduce your own predicates you can specify your own default.
app = None

The App object being handled by this request.

body_obj

JSON object, converted to an object.

You can use the App.load_json() directive to specify how to transform JSON to a Python object. By default, no conversion takes place, and body_obj is identical to the json attribute.

identity

Self-proclaimed identity of the user.

The identity is established using the identity policy. Normally this would be an instance of morepath.security.Identity.

If no identity is claimed or established, or if the identity is not verified by the application, the identity is the the special value morepath.security.NO_IDENTITY.

The identity can be used for authentication/authorization of the user, using Morepath permission directives.

lookup = None

The reg.Lookup object handling generic function calls.

class morepath.Response(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, **kw)

Response.

Extends webob.response.Response.

morepath.render_html(content, request)

Take string and return text/html response.

morepath.render_json(content, request)

Take dict/list/string/number content and return json response.

class morepath.security.Identity(userid, **kw)

Claimed identity of a user.

Note that this identity is just a claim; to authenticate the user and authorize them you need to implement Morepath permission directives.

Parameters:
  • userid – The userid of this identity
  • kw – Extra information to store in identity.
as_dict()

Export identity as dictionary.

This includes the userid and the extra keyword parameters used when the identity was created.

Returns:dict with identity info.
class morepath.security.IdentityPolicy

Identity policy API.

Implement this API if you want to have a custom way to establish identities for users in your application.

forget(response, request)

Forget identity on response.

Implements morepath.forget_identity, which is called from user logout code.

Remove identifying information from the response. This could delete a cookie or issue a basic auth re-authentication.

Parameters:
identify(request)

Establish what identity this user claims to have from request.

Parameters:request (morepath.Request.) – Request to extract identity information from.
Returns:morepath.security.Identity instance or morepath.security.NO_IDENTITY if identity cannot be established.
remember(response, request, identity)

Remember identity on response.

Implements morepath.remember_identity, which is called from user login code.

Given an identity object, store it on the response, for instance as a cookie. Some policies may not do any storing but instead retransmit authentication information each time in the request. Basic authentication is an example of such a non-storing policy.

Parameters:
class morepath.security.BasicAuthIdentityPolicy(realm='Realm')

Identity policy that uses HTTP Basic Authentication.

forget(response, request)

Forget identity on response.

This causes the browser to issue a basic authentication dialog. Warning: for basic auth, the browser in fact does not forget the information even if forget is called.

Parameters:
identify(request)

Establish claimed identity using request.

Parameters:request (morepath.Request.) – Request to extract identity information from.
Returns:morepath.security.Identity instance.
remember(response, request, identity)

Remember identity on response.

This is a no-op for basic auth, as the browser re-identifies upon each request in that case.

Parameters:
morepath.security.NO_IDENTITY = <morepath.security.NoIdentity object>
class morepath.Converter(decode, encode=None)

How to decode from strings to objects and back.

Only used for decoding for a list with a single value, will error if more or less than one value is entered.

Used for decoding/encoding URL parameters and path parameters.

Create new converter.

Parameters:
  • decode – function that given string can decode them into objects.
  • encode – function that given objects can encode them into strings.
class morepath.Config

Contains and executes configuration actions.

Morepath configuration actions consist of decorator calls on App instances, i.e. @App.view() and @App.path(). The Config object can scan these configuration actions in a package. Once all required configuration is scanned, the configuration can be committed. The configuration is then processed, associated with morepath.config.Configurable objects (i.e. App objects), conflicts are detected, overrides applied, and the configuration becomes final.

Once the configuration is committed all configured Morepath App objects are ready to be served using WSGI.

See setup(), which creates an instance with standard Morepath framework configuration. See also autoconfig() and autosetup() which help automatically load configuration from dependencies.

action(action, obj)

Register an action and obj with this config.

This is normally not invoked directly, instead is called indirectly by scan().

A Morepath directive decorator is an action, and obj is the function that was decorated.

Param:The Action to register.
Obj:The object to perform action on.
commit()

Commit all configuration.

  • Clears any previous configuration from all registered morepath.config.Configurable objects.
  • Prepares actions using prepared().
  • Actions are grouped by type of action (action class).
  • The action groups are executed in order of depends between their action classes.
  • Per action group, configuration conflicts are detected.
  • Per action group, extending configuration is merged.
  • Finally all configuration actions are performed, completing the configuration process.

This method should be called only once during the lifetime of a process, before the configuration is first used. After this the configuration is considered to be fixed and cannot be further modified. In tests this method can be executed multiple times as it automatically clears the configuration of its configurables first.

configurable(configurable)

Register a configurable with this config.

This is normally not invoked directly, instead is called indirectly by scan().

A App object’s registry attribute is a configurable.

Param:The morepath.config.Configurable to register.
prepared()

Get prepared actions before they are performed.

The preparation phase happens as the first stage of a commit. This allows configuration actions to complete their configuration, do error checking, or transform themselves into different configuration actions.

This calls Action.prepare() on all registered configuration actions.

Returns:An iterable of prepared action, obj combinations.
scan(package=None, ignore=None, recursive=True, onerror=None)

Scan package for configuration actions (decorators).

Register any found configuration actions with this object. This also includes finding any morepath.config.Configurable objects.

If given a package, it scans any modules and sub-packages as well recursively.

Parameters:
  • package – The Python module or package to scan. Optional; if left empty case the calling package is scanned.
  • ignore – A Venusian style ignore to ignore some modules during scanning. Optional. Defaults to ['.test', '.tests'].
  • recursive – Scan packages recursively. By default this is True. If set to False, only the __init__.py of a package is scanned.
  • onerror – onerror argument passed to Venusian’s scan.
class morepath.config.Configurable(extends=None, testing_config=None)

Object to which configuration actions apply.

Actions can be added to a configurable.

Once all actions are added, the configurable is executed. This checks for any conflicts between configurations and the configurable is expanded with any configurations from its extends list. Then the configurable is performed, meaning all its actions are performed (to it).

Parameters:
  • extends (list of configurables, single configurable.) – the configurables that this configurable extends. Optional.
  • testing_config – We can pass a config object used during testing. This causes the actions to be issued against the configurable directly instead of waiting for Venusian scanning. This allows the use of directive decorators in tests where scanning is not an option. Optional, default no testing config.
action(action, obj)

Register an action with configurable.

This is normally not invoked directly, instead is called indirectly by Config.commit().

Parameters:
  • action – The action to register with the configurable.
  • obj – The object that this action is performed on.
action_classes()

Get action classes sorted in dependency order.

action_extends(action_class)

Get actions for action class in extends.

actions()

Actions the configurable wants to register as it is scanned.

A configurable may want to register some actions as it is registered with the config system.

Should return a sequence of action, obj tuples.

clear()

Clear any previously registered actions.

This is normally not invoked directly, instead is called indirectly by Config.commit().

execute()

Execute actions for configurable.

group_actions()

Group actions into Actions by class.

class morepath.config.Action(configurable)

A configuration action.

A configuration action is performed on an object. Actions can conflict with each other based on their identifier and discriminators. Actions can override each other based on their identifier.

Can be subclassed to implement concrete configuration actions.

Action classes can have a depends attribute, which is a list of other action classes that need to be executed before this one is. Actions which depend on another will be executed after those actions are executed.

Initialize action.

Parameters:configurablemorepath.config.Configurable object for which this action was configured.
clone(**kw)

Make a clone of this action.

Keyword parameters can be used to override attributes in clone.

Used during preparation to create new fully prepared actions.

codeinfo()

Info about where in the source code the action was invoked.

By default there is no code info.

discriminators(configurable)

Returns a list of immutables to detect conflicts.

Parameters:configurablemorepath.config.Configurable object for which this action is being executed.

Used for additional configuration conflict detection.

group_key()

By default we group directives by their class.

Override this to group a directive with another directive, by returning that Directive class. It will create conflicts between those directives. Typically you’d do this when you are already subclassing from that directive too.

identifier(configurable)

Returns an immutable that uniquely identifies this config.

Parameters:configurablemorepath.config.Configurable object for which this action is being executed.

Used for overrides and conflict detection.

perform(configurable, obj)

Register whatever is being configured with configurable.

Parameters:
prepare(obj)

Prepare action for configuration.

Parameters:obj – The object that the action should be performed on.

Returns an iterable of prepared action, obj tuples.

class morepath.converter.ConverterRegistry

A registry for converters.

Used to decode/encode URL parameters and path variables used by the morepath.App.path() directive.

Is aware of inheritance.

argument_and_explicit_converters(arguments, converters)

Use explict converters unless none supplied, then use default args.

converter_for_explicit_or_type(c)

Given a converter or a type, turn it into an explicit one.

converter_for_explicit_or_type_or_list(c)

Given a converter or type or list, turn it into an explicit one.

Parameters:c – can either be a converter, or a type for which a converter can be looked up, or a list with a converter or a type in it.
Returns:a Converter instance.
converter_for_type(type)

Get converter for type.

Is aware of inheritance; if nothing is registered for given type it returns the converter registered for its base class.

Parameters:type – The type for which to look up the converter.
Returns:a morepath.Converter instance.
converter_for_value(v)

Get converter for value.

Is aware of inheritance; if nothing is registered for type of given value it returns the converter registered for its base class.

Parameters:value – The value for which to look up the converter.
Returns:a morepath.Converter instance.
explicit_converters(converters)

Given converter dictionary, make everything in it explicit.

This means types have converters looked up for them, and lists are turned into ListConverter.

register_converter(type, converter)

Register a converter for type.

Parameters:
  • type – the Python type for which to register the converter.
  • converter – a morepath.Converter instance.
class morepath.Directive(app)
morepath.directive

alias of morepath.directive

morepath.pdbsupport.set_trace(*args, **kw)

Set pdb trace as in import pdb; pdb.set_trace, ignores reg.

Use from morepath import pdbsupport; pdbsupport.set_trace() to use.

The debugger won’t step into reg, inspect or repoze.lru.