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
andstart_response
arguments.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.Request
alias 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 converters
dictionary 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_links
you 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
App
to do so likeApp.parent()
andApp.child()
.You also have to supply a
variables
argument to describe how to get the variables from an instance – this should be return the same variables as needed by thepath
directive in the app you are deferring to. This allowsdefer_class_links
to function asdefer_links
for 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_links
you can specify that link generation for instances ofmodel
is 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
App
to 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 self
passed 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
func
argument 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 takesself
andrequest
parameters as input. - template –
a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.
Use the
morepath.App.template_engine()
directive to define support for new template engines. - permission – a permission class. The model should have this permission, otherwise access to this view is forbidden. If omitted, the view function is public.
- internal – Whether this view is internal only. If
True
, the view is only useful programmatically 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 takesself
andrequest
parameters as input. - template –
a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.
Use the
morepath.App.template_engine()
directive to define support for new template engines. - permission – a permission class. The model should have this permission, otherwise access to this view is forbidden. If omitted, the view function is public.
- internal – Whether this view is internal only. If
True
, the view is only useful programmatically 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
json
andrequest
(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.App
subclass to mount. - variables – a function that given an app instance can construct the variables used in the path (including any URL parameters). If omitted, variables are retrieved from the app by using the arguments of the decorated function.
- converters – converters as for the
morepath.App.path()
directive. - required – list or set of names of those URL parameters which should be required, i.e. if missing a 400 Bad Request response is given. Any default value is ignored. Has no effect on path variables. Optional.
- get_converters – a function that returns a converter dictionary.
This function is called once during configuration time. It can
be used to programmatically supply converters. It is merged
with the
converters
dictionary, if supplied. Optional. - name – name of the mount. This name can be used with
Request.child()
to allow loose coupling between mounting application and mounted application. Optional, and if not supplied thepath
argument 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
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 theabsorb
argument.
-
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 returnTrue
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 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.KeyIndex
orreg.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_registry
class attribute ofmorepath.App
subclasses. 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
settings
attribute 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
before
another one are found before templates in a directoryafter
it. But you can leave bothbefore
andafter
out: template directories defined in sub-applications automatically have a higher priority than those defined in base applications.Parameters: - after – Template directory function this template directory
function to be under. The other template directory has a higher
priority. You usually want to use
over
. Optional. - before – Template directory function function this function should have priority over. Optional.
- name – The name under which to register this template directory, so that it can be overridden by applications that extend this one. If no name is supplied a default name is generated.
- 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_directories
argument, which is a list of absolute paths to directories that contain templates. It also gets asettings
argument, which is application settings that can be used to configure the loader.It should return an object that can load the template given the list of template directories.
-
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
,name
andoriginal_render
arguments. It should return acallable
that is a viewrender
function: take acontent
andrequest
object and return amorepath.Response
instance. This render callable should render the return value of the view with the template supplied through itstemplate
argument.
-
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
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.
- 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
identity
argument which contains the claimed identity. It should returnTrue
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.
-
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.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 therender
parameter expects as input. This function should take the object to render and the request. func:morepath.render_json for instance expects as its first argument a Python object such as a dict that can be serialized to JSON.See also
morepath.App.json()
andmorepath.App.html()
.Parameters: - model – the class of the model for which this view is registered.
The
self
passed into the view function is an instance of the model (or of a subclass). - render – an optional function that can render the output of the
view function to a response, and possibly set headers such as
Content-Type
, etc. This function takesself
andrequest
parameters as input. - template –
a path to a template file. The path is relative to the directory this module is in. The template is applied to the content returned from the decorated view function.
Use the
morepath.App.template_loader()
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.Request
instance, then uses meth:App.publish get themorepath.Response
instance.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
variables
the parameters that go to itsmount
function.Returns the mounted application object, with its
parent
attribute set to this app object, orNone
if 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.
Returns: the set of discovered app clasess.
-
forget_identity
(response, request)¶ Modify response so that identity is forgotten by client.
Parameters: - response –
morepath.Response
to forget identity on. - request –
morepath.Request
- response –
-
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 implementmorepath.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.
-
remember_identity
(response, request, identity)¶ Modify response so that identity is remembered by client.
Parameters: - response –
morepath.Response
to remember identity on. - request –
morepath.Request
- identity –
morepath.Identity
- response –
-
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 itsmount
function.Returns the mounted application object, with its
parent
attribute set to the same parent as this one, orNone
if such a sibling application does not exist.
-
logger_name
= 'morepath.directive'¶ Prefix used by dectate to log configuration actions.
-
lookup
¶ Get the
reg.Lookup
for this application.Returns: a reg.Lookup
instance.
-
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.Request
instance and returns amorepath.Response
instance.
-
root
¶ The root application.
-
settings
¶ Returns the settings bound to this app.
Works the same way as
morepath.generic.settings()
. Unlike callingmorepath.settings
however, 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
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 theinstall_requires
list of thesetup.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 namedmyapp
the package must be namedmyapp
as well (notmy-app
orMyApp
).
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 anImportError
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 aspytest
ornose
. 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 theignore
argument, for instance using['special_package']
. You then can usescan()
for that package, with a customignore
argument that excludes the modules that generate import errors.See also
scan()
.Parameters: ignore – ignore to ignore some modules during scanning. Optional. If ommitted, ignore .test
and.tests
packages by default. Seeimportscan.scan()
for more details.- The package is made available using a
-
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 eachApp
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. Useignore_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] optional arguments: -h, --help show this help message and exit -p PORT, --port PORT TCP port on which to listen (default: 5000) -H HOST, --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 takend from the value of the arguments passed tomorepath.run()
.
-
morepath.
settings
()¶ Return current settings object.
In it are sections, and inside of the sections are the setting values. If there is a
logging
section and aloglevel
setting in it, this is how you would access it:settings().logging.loglevel
Deprecated: use the property
morepath.App.settings
instead.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
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 eitherwebob.exc.HTTPOk
orwebob.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.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.
-
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.LinkError
is raised.None
is treated specially: ifNone
is 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
None
is 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.
-
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
andrequest_method
. The defaultname
is empty, so the default view is looked up, and the defaultrequest_method
isGET
. If you introduce your own predicates you can specify your own default.
-
app
= None¶ morepath.App
instance 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_obj
is identical to thejson
attribute.
-
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.Lookup
object 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.Request
instance.
Returns: a
morepath.Response
instance withcontent
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.
-
morepath.
remember_identity
(response, request, identity)¶ Modify response so that identity is remembered by client.
Deprecated: use the method
morepath.App.remember_identity()
instead.Parameters: - response –
morepath.Response
to remember identity on. - request –
morepath.Request
- identity –
morepath.Identity
- response –
-
morepath.
forget_identity
(response, request)¶ Modify response so that identity is forgotten by client.
Deprecated: use the method
morepath.App.forget_identity()
instead.Parameters: - response –
morepath.Response
to 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.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: - 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.Identity
instance ormorepath.NO_IDENTITY
if identity cannot be established.
-
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: - 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>¶ 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.
enable_implicit
()¶ Enable implicit Reg lookups.
By default this is turned on. This means Morepath does not require a
lookup
argument when you use generic functions such asmorepath.settings()
. This lookup argument is implicitly determined from the application that is mounted.Deprecated You no longer need to choose between implicit or explicit lookup for generic functions, as the generic functions that are part of the API have all been deprecated.
-
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()
Deprecated You no longer need to choose between implicit or explicit lookup for generic functions, as the generic functions that are part of the API have all been deprecated.
morepath.error
– exception classes¶
The exception classes used by Morepath.
Morepath republishes some configuration related errors from Dectate:
dectate.ConfigError
dectate.ConflictError
dectate.DirectiveReportError
dectate.DirectiveError
dectate.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.