API

morepath

This is the main public API of Morepath.

Additional public APIs can be imported from the morepath.error and morepath.pdbsupport modules. For custom directive implementations that interact with core directives for grouping or subclassing purposes, or that need to use one of the Morepath registries, you may need to import from morepath.directive.

The other submodules are considered private. If you find yourself needing to import from them in application or extension code, please report an issue about it on the Morepath issue tracker.

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.

Subclasses from dectate.App, which provides the dectate.App.directive() decorator that lets you register new directives.

request_class

alias of Request

classmethod clean()

A method that sets or restores the state of the class.

Normally Dectate only sets up configuration into the config attribute, but in some cases you may touch other aspects of the class during configuration time. You can override this classmethod to set up the state of the class in its pristine condition.

classmethod commit()

Commit the app, and recursively, the apps mounted under it.

Mounted apps are discovered in breadth-first order.

Returns:

the set of discovered app clasess.

classmethod init_settings(settings)

Pre-fill the settings before the app is started.

Add settings to App, which can act as normal, can be overridden, etc.

Parameters:

settings – a dictionary of setting sections which contain dictionaries of settings.

classmethod mounted_app_classes(callback=None)

Returns a set of this app class and any mounted under it.

This assumes all app classes involved have already been committed previously, for instance by morepath.App.commit().

Mounted apps are discovered in breadth-first order.

The optional callback argument is used to implement morepath.App.commit().

Parameters:

callback – a function that is called with app classes as its arguments. This can be used to do something with the app classes when they are first discovered, like commit them. Optional.

Returns:

the set of app classes.

__call__(environ, start_response)

This app as a WSGI application.

See the WSGI spec for more information.

Uses App.request() to generate a morepath.Request instance, then uses meth:App.publish get the morepath.Response instance.

Parameters:
  • environ – WSGI environment

  • start_response – WSGI start_response

Returns:

WSGI iterable.

__init__()
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.

forget_identity(response, request)

Modify response so that identity is forgotten by client.

Parameters:
get_view(obj, request)

Get the view that represents the obj in the context of a request.

This view is a representation of the obj that can be rendered to a response. It may also return a morepath.Response directly.

Predicates are installed in morepath.core that inspect both obj and request to see whether a matching view can be found.

You can also install additional predicates using the morepath.App.predicate() and morepath.App.precicate_fallback() directives.

Parameters:
  • obj – model object to represent with view.

  • requestmorepath.Request instance.

Returns:

morepath.Response object, or webob.exc.HTTPNotFound if view cannot be found.

remember_identity(response, request, identity)

Modify response so that identity is remembered by client.

Parameters:
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.

config = <dectate.app.Config object>

Config object that contains the configuration after commit.

This is installed when the class object is initialized, so during import-time when you use the class statement and subclass dectate.App, but is only filled after you commit the configuration.

This keeps the final configuration result after commit. It is a very dumb object that has no methods and is just a container for attributes that contain the real configuration.

dectate = <dectate.config.Configurable object>

A dectate Configurable instance is installed here.

This is installed when the class object is initialized, so during import-time when you use the class statement and subclass dectate.App.

This keeps tracks of the registrations done by using directives as long as committed configurations.

logger_name = 'morepath.directive'

Prefix used by dectate to log configuration actions.

parent = None

The parent in which this app was mounted.

publish

Publish functionality wrapped in tweens.

You can use middleware (Tweens) that can hooks in before a request is passed into the application and just after the response comes out of the application. Here we use morepath.tween.TweenRegistry.wrap() to wrap the morepath.publish.publish() function into the configured tweens.

This property uses morepath.reify.reify() so that the tween wrapping only happens once when the first request is handled and is cached afterwards.

Returns:

a function that a morepath.Request instance and returns a morepath.Response instance.

root

The root application.

property settings

Returns the settings bound to this app.

morepath.scan(package=None, ignore=None, handle_error=None)

Scan package for configuration actions (decorators).

It scans by recursively importing the package and any modules in it, including any sub-packages.

Register any found directives with their app classes.

Parameters:
  • package – The Python module or package to scan. Optional; if left empty case the calling package is scanned.

  • ignore – A list of packages to ignore. Optional. Defaults to ['.test', '.tests']. See importscan.scan() for details.

  • handle_error – Optional error handling function. See importscan.scan() for details.

morepath.autoscan(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 name 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 simply recursively imports everything in those packages, except for test directories.

In addition to calling this function you can also import modules that use Morepath directives manually, and you can use scan() to automatically import everything in a single package.

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

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

autoscan 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 autoscan using the ignore argument, for instance using ['special_package']. You then can use scan() for that package, with a custom ignore argument that excludes the modules that generate import errors.

See also scan().

Parameters:

ignore – ignore to ignore some modules during scanning. Optional. If omitted, ignore .test and .tests packages by default. See importscan.scan() for more details.

morepath.commit(*apps)

Commit one or more app classes

A commit causes the configuration actions to be performed. The resulting configuration information is stored under the .config class attribute of each App subclass supplied.

This function may safely be invoked multiple times – each time the known configuration is recommitted.

Parameters:

*apps – one or more App subclasses to perform configuration actions on.

morepath.run(wsgi, host='127.0.0.1', port=5000, prog=None, ignore_cli=False, callback=None)

Uses wsgiref.simple_server to run an application for debugging purposes.

By default, this function looks at the command line for arguments specified with the --host or --port options. These override the actual arguments passed to this function. Use ignore_cli=True to disable this behavior.

Under non-exceptional circumstances this function never returns.

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

Parameters:
  • wsgi (callable) – WSGI app.

  • host (str) – hostname or IP address on which to listen.

  • port (int) – TCP port on which to listen.

  • prog (str or None) – the name of the program displayed by diagnostics and help.

  • ignore_cli (bool) – whether to ignore sys.argv.

  • callback (function(server) or None) – function invoked after the creation of the server.

Returns:

never.

Note

Unless ignore_cli is true, this function provides a full-featured command-line parser. Its help message describes how to use it:

usage: <script name> [-h] [-p PORT] [-H HOST]

options:
  -h, --help       show this help message and exit
  -p, --port PORT  TCP port on which to listen (default: 5000)
  -H, --host HOST  hostname or IP address on which to listen
                   (default: 127.0.0.1)

The default values for the --port and --host options are taken from the value of the arguments passed to morepath.run().

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

Request.

Extends webob.request.BaseRequest

after(func)

Call a function with the response after a successful request.

A request is considered successful if the HTTP status is a 2XX or a 3XX code (e.g. 200 OK, 204 No Content, 302 Found). In this case after is called.

A request is considered unsuccessful if the HTTP status lies outside the 2XX-3XX range (e.g. 403 Forbidden, 404 Not Found, 500 Internal Server Error). Usually this happens if an exception occurs. In this case after is not called.

Some exceptions indicate a successful request however and their occurrence still leads to a call to after. These exceptions inherit from either webob.exc.HTTPOk or webob.exc.HTTPRedirection.

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')
Parameters:

func – callable that is called with response

Returns:

func argument, not wrapped

Create a link (URL) to a view on a class.

Given a model class and a variables dictionary, create a link based on the path registered for the class and interpolate the variables.

If you have an instance of the model available you’d link to the model instead, but in some cases it is expensive to instantiate the model just to create a link. In this case class_link can be used as an optimization.

The morepath.App.defer_class_links() directive can be used to defer link generation for a particular class (if this app doesn’t handle them) to another app.

Note that the morepath.App.defer_links() directive has no effect on class_link, as it needs an instance of the model to work, which is not available.

If no link can be constructed for the model class, a morepath.error.LinkError is raised. This error is also raised if you don’t supply enough variables. Additional variables not used in the path are interpreted as URL parameters.

Parameters:
  • model – the model class to link to.

  • variables – a dictionary with as keys the variable names, and as values the variable values. These are used to construct the link URL. If omitted, the dictionary is treated as containing no variables.

  • name – the name of the view to link to. If omitted, the the default view is looked up.

  • 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.

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 morepath.error.LinkError is raised. None is treated specially: if None is passed in the default value is returned.

The morepath.App.defer_links() or morepath.App.defer_class_links() directives can be used to defer link generation for all instances of a particular class (if this app doesn’t handle them) to another app.

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.

Prefix to all links created by this request.

Parameters:

app – Optionally use the given app to create the link. This leads to use of the link prefix configured for the given app. This parameter is mainly used internally for link creation.

reset()

Reset request.

This resets the request back to the state it had when request processing started. This is used by more.transaction when it retries a transaction.

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

morepath.App instance currently handling request.

identity

Self-proclaimed identity of the user.

The identity is established using the identity policy. Normally this would be an instance of morepath.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.NO_IDENTITY.

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

unconsumed

Stack of path segments that have not yet been consumed.

See morepath.publish.

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

Response.

Extends webob.response.Response.

morepath.render_html(content, request)

Take string and return text/html response.

Parameters:
  • content – contnet as returned from view function.

  • request – a morepath.Request instance.

Returns:

a morepath.Response instance with content as the body.

morepath.render_json(content, request)

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

This respects the morepath.App.dump_json() directive that can be used to serialize any object to JSON. By default this serializes Python objects like dicts, strings to JSON.

Parameters:
  • content – content as returned from view function.

  • request – a morepath.Request instance.

Returns:

a morepath.Response instance with a serialized JSON body.

morepath.redirect(location)

Return a response object that redirects to location.

Parameters:

location – a URL to redirect to.

Returns:

a webob.exc.HTTPFound response object. You can return this from a view to redirect.

class morepath.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.

userid

The user ID of the identity.

May be None if no particular identity was established.

class morepath.IdentityPolicy

Identity policy API.

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

abstractmethod forget(response, request)

Forget identity on response.

Implements morepath.App.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:
abstractmethod identify(request)

Establish what identity this user claims to have from request.

Parameters:

request (morepath.Request.) – Request to extract identity information from.

Returns:

morepath.Identity instance or morepath.NO_IDENTITY if identity cannot be established.

abstractmethod remember(response, request, identity)

Remember identity on response.

Implements morepath.App.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.

Parameters:
morepath.NO_IDENTITY = <morepath.authentication.NoIdentity object>

The user is not yet logged in.

The request is anonymous.

morepath.EXCVIEW = <function excview_tween_factory>

Exception views.

If an exception is raised by application code and a view is declared for that exception class, use it.

If no view can be found, raise it all the way up – this will be a 500 internal server error and an exception logged.

morepath.HOST_HEADER_PROTECTION = <function poisoned_host_header_protection_tween_factory>

Protect Morepath applications against the most basic host header poisoning attacts.

The regex approach has been copied from the Django project. To find more about this particular kind of attack have a look at the following references:

class morepath.Converter(decode, encode=None)

Decode from strings to objects and back.

Used internally by the morepath.App.converter() directive.

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.

decode(strings)

Decode list of strings into Python value.

String must have only a single entry.

Parameters:

strings – list of strings.

Returns:

Python value

encode(value)

Encode Python value into list of strings.

Parameters:

value – Python value

Returns:

List of strings with only a single entry

is_missing(value)

True is a given value is the missing value.

morepath.dispatch_method(*predicates, **kw)

Decorator to make a method on a context class dispatch.

This takes the predicates to dispatch on as zero or more parameters.

Parameters:
  • predicates

    sequence of Predicate instances to do the dispatch on. You create predicates using reg.match_instance(), reg.match_key(), reg.match_class(), or with a custom predicate class.

    You can also pass in plain string argument, which is turned into a reg.match_instance() predicate.

  • get_key_lookup – a function that gets a PredicateRegistry instance and returns a key lookup. A PredicateRegistry instance is itself a key lookup, but you can return a caching key lookup (such as reg.DictCachingKeyLookup or reg.LruCachingKeyLookup) to make it more efficient.

  • first_invocation_hook – a callable that accepts an instance of the class in which this decorator is used. It is invoked the first time the method is invoked.

morepath.error – exception classes

The exception classes used by Morepath.

Morepath republishes some configuration related errors from Dectate:

Morepath specific errors:

exception morepath.error.AutoImportError(module_name)

Raised when Morepath fails to import a module during autoscan.

exception morepath.error.TrajectError

Raised when path supplied to traject is not allowed.

exception morepath.error.LinkError

Raised when a link cannot be made.

exception morepath.error.TopologicalSortError

Raised if dependencies cannot be sorted topologically.

This is due to circular dependencies.

morepath.pdbsupport – debugging support

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.