Morepath API

class morepath.App(**context)

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.

@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().
@function(target, *sources)

Register function as implementation of generic 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. This is a layer over reg.IRegistry.register().

The target argument is a generic function, so a Python function marked with either reg.generic() or with reg.classgeneric().

Parameters:
  • target (function object) – the generic function to register an implementation for.
  • sources – classes of parameters to register for.
@html(model, render=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.
  • 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 an identity policy, which should have identify, remember and forget methods.

@json(model, render=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.
  • 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.
@mount(path, app, 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 dictionary with the required variables for the mounted app. The variables are declared in the morepath.App constructor.

Parameters:
  • path – the path to mount the application on.
  • app – the morepath.App subclass to mount.
  • 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(name, order, default, index=<class 'reg.predicate.KeyIndex'>)

Register custom view predicate.

The decorated function gets model and request (a morepath.Request object) parameters.

From this information it should calculate a predicate value and return it. You can then pass these extra predicate arguments to morepath.App.view() and this view is only found if the predicate matches.

Parameters:
  • name – the name of the view predicate.
  • order (int) – when this custom view predicate should be checked compared to the others. A lower order means a higher importance.
  • default – the default value for this view predicate. This is used when the predicate is omitted or None when supplied to the morepath.App.view() directive. This is also used when using Request.view() to render a view.
  • index – the predicate index to use. Default is reg.KeyIndex which matches by name.
@predicate_fallback(name)

For a given predicate name, register fallback view.

The decorated function gets self and request parameters.

The fallback view is a view that gets called when the named predicate does not match and no view has been registered that can handle that case.

Parameters:name – the name of the predicate.
@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.
@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, 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. morepath.render_json() for instance expects 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.
  • 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 – predicates to match this view on. Use morepath.ANY for a predicate if you don’t care what the value is. If you don’t specify a predicate, the default value is used. Standard predicate values are name and request_method, but you can install your own using the morepath.App.predicate() directive.
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.

Parameters:environ – WSGI environment
Returns:morepath.Request instance
lookup

Get the reg.Lookup for this application.

Returns:a reg.Lookup instance.
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 loads all needed Morepath configuration from all packages automatically. These packages do need to be made available using a setup.py file including currect install_requires information so that they can be found using setuptools.

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.

See also autosetup().

Parameters:ignoreVenusian style ignore to ignore some modules during scanning. Optional.
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.

Parameters:ignoreVenusian style ignore to ignore some modules during scanning. Optional.
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(*args, **kw)

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
class morepath.Request(environ)

Request.

Extends webob.request.BaseRequest

after(func)

Call function with response after this request is done.

Can be used explicitly:

def myfunc(response):
    response.headers.add('blah', 'something')
request.after(my_func)

or as a decorator:

@request.after
def myfunc(response):
    response.headers.add('blah', 'something')
Parameters:func – callable that is called with response
Returns:func argument, not wrapped
child(app, **variables)

Obj to call Request.link() or Request.view() on child.

Get an object that represents the application mounted in this app. You can call link and view on it.

Parameters:
  • app – either subclass of morepath.App that you want to link to, or a string. This string represents the name of the mount (by default it’s the path under which the mount happened).
  • **variables

    Keyword parameters. These are the mount variables under which the app was mounted.

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

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.
sibling(app, **variables)

Obj to call Request.link() or Request.view() on sibling.

Get an object that represents the application mounted as a sibling to this app, so the child of the parent. You can call link and view on it.

Parameters:
  • app – either subclass of morepath.App that you want to link to, or a string. This string represents the name of the mount (by default it’s the path under which the mount happened).
  • **variables

    Keyword parameters. These are the mount variables under which the app was mounted.

view(obj, default=None, **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.
  • 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.
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.

parent

Obj to call Request.link() or Request.view() on parent.

Get an object that represents the parent app that this app is mounted inside. You can call link and view on it.

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)

Take string and return text/html response.

morepath.render_json(content)

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

morepath.ANY = <ANY>
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.BasicAuthIdentityPolicy(realm='Realm')

Identity policy that uses HTTP Basic Authentication.

Note that this policy does not do any password validation. You’re expected to do so using permission directives.

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 at 0x7f8d8d7ee090>
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 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)

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.
Recursive:Scan packages recursively. By default this is True. If set to False, only the __init__.py of a package is scanned.
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