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
environandstart_responsearguments.Subclasses from
dectate.App, which provides thedectate.App.directive()decorator that lets you register new directives.-
request_class¶ The class of the Request to create. Must be a subclass of
morepath.Request.By default the request class is
morepath.Requestalias of
Request
-
classmethod
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 convertersdictionary in themorepath.App.path()directive, or is deduced from the value of the default argument of the decorated model function or class usingtype().
-
classmethod
defer_class_links(model, variables)¶ Defer class link generation for model class to mounted app.
With
defer_class_linksyou can specify that link generation for model classes is to be handled by a returned mounted app if it cannot be handled by the given app itself.Request.class_link(),Request.link()andRequest.view()are affected by this directive.The decorated function gets an instance of the application, the model class and a variables dict. It should return another application that it knows can create links for this class. The function uses navigation methods on
Appto do so likeApp.parent()andApp.child().You also have to supply a
variablesargument to describe how to get the variables from an instance – this should be return the same variables as needed by thepathdirective in the app you are deferring to. This allowsdefer_class_linksto function asdefer_linksfor model objects as well.Parameters: - model – the class for which we want to defer linking.
- variables – a function that given a model object can construct the variables used in the path (including any URL parameters).
-
classmethod
defer_links(model)¶ Defer link generation for model to mounted app.
With
defer_linksyou can specify that link generation for instances ofmodelis to be handled by a returned mounted app if it cannot be handled by the given app itself.Request.link()andRequest.view()are affected by this directive. Note thatRequest.class_link()is not affected by this directive, but you can usemorepath.App.defer_class_links()instead.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
Appto do so likeApp.parent()andApp.child().Parameters: model – the class for which we want to defer linking.
-
classmethod
dump_json(model=<type 'object'>)¶ Register a function that converts model to JSON.
The decorated function gets
self(model instance) andrequest(morepath.Request) parameters. The function should return an JSON object. That is, a Python object that can be dumped to a JSON string usingjson.dump.Parameters: model – the class of the model for which this function is registered. The selfpassed into the function is an instance of the model (or of a subclass). By default the model isobject, meaning we register a function for all model classes.
-
classmethod
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
funcargument is a generic dispatch function, so a Python function marked withapp.dispatch()orapp.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.
-
classmethod
html(model, render=None, template=None, permission=None, internal=False, **predicates)¶ Register HTML view.
This is like
morepath.App.view(), but withmorepath.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 takesselfandrequestparameters 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 usingmorepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view isFalse, 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.
-
classmethod
identity_policy()¶ Register identity policy.
The decorated function should return an instance of
morepath.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.
-
classmethod
json(model, render=None, template=None, permission=None, internal=False, **predicates)¶ Register JSON view.
This is like
morepath.App.view(), but withmorepath.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 takesselfandrequestparameters 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 usingmorepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view isFalse, 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.
-
classmethod
link_prefix()¶ 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 parameter. The function should return a string.
-
classmethod
load_json()¶ Register a function that converts JSON to an object.
The decorated function gets
jsonandrequest(morepath.Request) parameters. The function should return a Python object based on the given JSON.
-
classmethod
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.Appsubclass 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
convertersdictionary, 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 thepathargument is taken as the name.
-
classmethod
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
Noneif 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
requestparameter 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.Converterinstance. - 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
convertersdictionary, 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 theremainingvariable.
-
classmethod
permission_rule(model, permission, identity=<class 'morepath.authentication.Identity'>)¶ Declare whether a model has a permission.
The decorated function receives
model, permission` (instance of any permission object) andidentity(morepath.Identity) parameters. The decorated function should returnTrueonly 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 specialmorepath.NO_IDENTITY.
-
classmethod
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 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
reg.KeyIndexorreg.ClassIndex. - before – predicate function this function wants to have priority over.
- after – predicate function we want to have priority over this one.
-
classmethod
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
-
classmethod
setting(section, name)¶ Register application setting.
An application setting is registered under the
.config.settings_registryclass attribute ofmorepath.Appsubclasses. 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.
-
classmethod
setting_section(section)¶ Register application setting in a section.
An application settings are registered under the
settingsattribute ofmorepath.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.
-
classmethod
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
beforeanother one are found before templates in a directoryafterit. But you can leave bothbeforeandafterout: 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.
- after – Template directory function this template directory
function to be under. The other template directory has a higher
priority. You usually want to use
-
classmethod
template_loader(extension)¶ Create a template loader.
The decorated function gets a
template_directoriesargument, which is a list of absolute paths to directories that contain templates. It also gets asettingsargument, 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.
-
classmethod
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,nameandoriginal_renderarguments. It should return acallablethat is a viewrenderfunction: take acontentandrequestobject and return amorepath.Responseinstance. This render callable should render the return value of the view with the template supplied through itstemplateargument.
-
classmethod
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
undertween factory. Optional. - over – This tween factory produces a tween that wants to
wrap the tween produced by the over
tweenfactory. 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.
- under – This tween factory produces a tween that wants to
be wrapped by the tween produced by the
-
classmethod
verify_identity(identity=<type 'object'>)¶ Verify claimed identity.
The decorated function gives a single
identityargument which contains the claimed identity. It should returnTrueonly 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
Trueas 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.
-
classmethod
view(model, render=None, template=None, permission=None, internal=False, **predicates)¶ Register a view for a model.
The decorated function gets
self(model instance) andrequest(morepath.Request) parameters. The function should return either a (unicode) string that is the response body, or amorepath.Responseobject.If a specific
renderfunction is given the output of the function is passed to this first, and the function could return whatever therenderparameter 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()andmorepath.App.html().Parameters: - model – the class of the model for which this view is registered.
The
selfpassed 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 takesselfandrequestparameters 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()andmorepath.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 usingmorepath.Request.view(), but will not be published on the web. It will be as if the view is not there. By default a view isFalse, 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.
- model – the class of the model for which this view is registered.
The
-
__call__(environ, start_response)¶ This app as a WSGI application.
See the WSGI spec for more information.
Uses
App.request()to generate amorepath.Requestinstance, then uses meth:App.publish get themorepath.Responseinstance.Parameters: - environ – WSGI environment
- start_response – WSGI start_response
Returns: WSGI iterable.
-
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
variablesthe parameters that go to itsmountfunction.Returns the mounted application object, with its
parentattribute set to this app object, orNoneif this application cannot be mounted in this one.
-
classmethod
commit()¶ Commit the app, and recursively, the apps mounted under it.
Mounted apps are discovered in breadth-first order.
This method supersedes the deprecated function
morepath.autocommit().Returns: the set of discovered apps.
-
request(environ)¶ Create a
Requestgiven WSGI environment for this app.Parameters: environ – WSGI environment Returns: morepath.Requestinstance
-
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
variablesthe parameters that go to itsmountfunction.Returns the mounted application object, with its
parentattribute set to the same parent as this one, orNoneif such a sibling application does not exist.
-
logger_name= 'morepath.directive'¶ Prefix used by dectate to log configuration actions.
-
lookup¶ Get the
reg.Lookupfor this application.Returns: a reg.Lookupinstance.
-
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 themorepath.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.Requestinstance and returns amorepath.Responseinstance.
-
root¶ The root application.
-
settings¶ Returns the settings bound to this app.
Works the same way as
morepath.generic.settings(). Unlike callingmorepath.settingshowever, this property does not rely on the global lookup.
-
-
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']. Seeimportscan.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
Appinstances, 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.pyfile. - The package or a dependency of the package includes
morepathin theinstall_requireslist of thesetup.pyfile. - The
setup.pyname is the same as the name of the distributed package or module. For example: if the module inside the package is namedmyappthe package must be namedmyappas well (notmy-apporMyApp).
If the
setup.pyname 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.
autoscanalways ignores.testand.testssub-packages – these are assumed never to contain useful Morepath configuration and are not scanned.autoscancan fail with anImportErrorwhen 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 aspytestornose. If those tests are in a.testor.testssub-package they are automatically ignored, however.If you have a special package with such expected import errors, you can exclude them from
autoscanusing theignoreargument, for instance using['special_package']. You then can usescan()for that package, with a customignoreargument that excludes the modules that generate import errors.See also
scan().Parameters: ignore – ignore to ignore some modules during scanning. Optional. If ommitted, ignore .testand.testspackages by default. Seeimportscan.scan()for more details.- The package is made available using a
-
morepath.autosetup(ignore=None)¶ Automatically scan and commit Morepath configuration.
As with
morepath.autoscan(), 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.
autosetupalways ignores.testand.testssub-packages – these are assumed never to contain useful Morepath configuration and are not scanned.autosetupcan fail with anImportErrorwhen 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 aspytestornose. If those tests are in a.testor.testssub-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.autoscan()with an ignore for this package, and then doing a manualscan()for that package with the resulting config object. There you can add a customignoreargument that excludes the modules that generate import errors.Parameters: ignore – ignore to ignore some modules during scanning. Optional. If ommitted, ignore .testand.testspackages by default. Seeimportscan.scan()for more details.Deprecated: use the function
morepath.autoscan(), instead.autosetupis now completely equivalent to it.
-
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
.configclass attribute of eachAppsubclass supplied.This function may safely be invoked multiple times – each time the known configuration is recommitted.
Parameters: *apps – one or more Appsubclasses to perform configuration actions on.
-
morepath.autocommit()¶ Automatically commit all
Appsubclasses.Dectate keeps track of all
Appsubclasses that have been imported. You can automatically commit configuration for all of them.Deprecated: use the explicit
App.commit()method instead. SinceApp.commit()is defined to commit all dependent applications that are needed this makes it more explicit than this one.
-
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
loggingsection and aloglevelsetting in it, this is how you would access it:settings().logging.loglevel
Returns: current settings object for this app.
-
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
afteris 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
afteris not called.Some exceptions indicate a successful request however and their occurrence still leads to a call to
after. These exceptions inherit from eitherwebob.exc.HTTPOkorwebob.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
-
class_link(model, variables=None, name='', app=<SAME_APP>)¶ 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 onclass_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.LinkErroris 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.
-
link(obj, name='', default=None, app=<SAME_APP>)¶ 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.LinkErroris raised.Noneis treated specially: ifNoneis passed in the default value is returned.The
morepath.App.defer_links()ormorepath.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
Noneis passed in, the default value is returned. By default this isNone. - 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.
- obj – the model instance to link to, or
-
link_prefix()¶ 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
Noneif 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
Noneif 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_linksdirective can be used to change the default app for all instances of a particular class. - predicates – extra predicates to modify view
lookup, such as
nameandrequest_method. The defaultnameis empty, so the default view is looked up, and the defaultrequest_methodisGET. If you introduce your own predicates you can specify your own default.
-
app= None¶ morepath.Appinstance currently handling 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, andbody_objis identical to thejsonattribute.
-
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.
-
lookup= None¶ The
reg.Lookupobject handling generic function calls.
-
unconsumed= None¶ 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, **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.Requestinstance.
Returns: a
morepath.Responseinstance withcontentas 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.Requestinstance.
Returns: a
morepath.Responseinstance 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.HTTPFoundresponse 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.
-
morepath.remember_identity()¶ Modify response so that identity is remembered by client.
Parameters: - response –
morepath.Responseto remember identity on. - request –
morepath.Request - identity –
morepath.Identity
- response –
-
morepath.forget_identity()¶ Modify response so that identity is forgotten by client.
Parameters: - response –
morepath.Responseto forget identity on. - request –
morepath.Request
- response –
-
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.
-
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: - response (
morepath.Response) – response object on which to forget identity. - request (
morepath.Request) – request object.
- response (
-
identify(request)¶ Establish what identity this user claims to have from request.
Parameters: request ( morepath.Request.) – Request to extract identity information from.Returns: morepath.Identityinstance ormorepath.NO_IDENTITYif 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.
Parameters: - response (
morepath.Response) – response object on which to store identity. - request (
morepath.Request) – request object. - identity (
morepath.Identity) – identity to remember.
- response (
-
-
morepath.NO_IDENTITY= <morepath.authentication.NoIdentity object>¶ The identity if the request is anonymous.
The user has not yet logged in.
-
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>¶ Protects 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.enable_implicit()¶ Enable implicit Reg lookups.
By default this is turned on. This means Morepath does not require a
lookupargument when you use generic functions such asmorepath.settings(). This lookup argument is implicitly determined from the application that is mounted.
-
morepath.disable_implicit()¶ Disable implicit Reg lookups.
The Morepath core itself does not rely on any implicit behavior, and it is therefore disabled for many of the tests.
How to disable implicit lookups for all tests in a module:
def setup_module(module): morepath.disable_implicit()
morepath.error – exception classes¶
The exception classes used by Morepath.
Morepath republishes some configuration related errors from Dectate:
dectate.ConfigErrordectate.ConflictErrordectate.DirectiveReportErrordectate.DirectiveErrordectate.TopologicalSortError
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.