Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More

The lino.core.requests module

This is the reference documentation about the lino.core.requests module, which defines classes for representing action requests.

See also introduction in Using action requests.

As an application developer you don’t instantiate this yourself, you get it e.g. as an argument in methods you override,

“”” Holds information about an individual web request and provides methods like

An ActionRequest is also a BaseRequest and inherits its methods.

An ActionRequest is instantiated from different shortcut methods:

  • lino.core.actors.Actor.request()

  • lino.core.actions.Action.request()

class lino.core.requests.BaseRequest

The return value of rt.login() is a basic request.

Inherits from lino.utils.site_config.SiteConfigPointer. Base class for ActionRequest.

Used in tested documents.

parse_req(self, request, rqdata, **kw)

Parse the given incoming HttpRequest and set up this action request from it.

The mt url param is parsed only when needed. Usually it is not needed because the master_class is constant and known per actor. But there are exceptions:

setup_from(self, other)

Copy certain values (renderer, user, subst_user & requesting_panel) from this request to the other.

Deprecated. You should rather instantiate a request and specify parent instead. Or use spawn_request() on parent.

spawn_request(self, **kw)

Create a new request of same class which inherits from this one.

spawn(self, spec=None, **kw)

Deprecated. Use the more explicit spawn_request() if possible.

Create a new action request using default values from this one and the action specified by spec.

The first argument, spec can be:

  • a string with the name of a model, actor or action

  • a BoundAction instance

  • another action request (deprecated use)

get_printable_context(self, **kw)

Adds a series of names to the context used when rendering printable documents.

set_selected_pks(self, *selected_pks)

Given a tuple of primary keys, set selected_rows to a list of corresponding database objects.

TODO: Explain why the special primary keys -99998 and -99999 are filtered out.

get_permission(self)

Whether this request has permission to run. obj can be None if the action is a list action (whose select_rows is False).

set_response(self, **kw)

Set (some part of) the response to be sent when the action request finishes. Allowed keywords are documented in ValidActionResponses.

This does not yet respond anything, it is stored until the action has finished. The response might be overwritten by subsequent calls to set_response().

Lino.handle_action_result() will get these instructions as keywords and thus will not know the order in which they have been issued. This is a design decision. We want that, when writing custom actions, the order of these instructions does not matter.

error(self, e=None, message=None, **kw)

Shortcut to set_response() used to set an error response.

The first argument should be either an exception object or a text with a message.

If a message is not explicitly given, Lino escapes any characters with a special meaning in HTML. For example:

NotImplementedError: <dl> inside <text:p>

will be converted to:

NotImplementedError: &lt;dl&gt; inside &lt;text:p&gt;
success(self, message=None, alert=None, **kw)

Tell the client to consider the action as successful. This is the same as set_response() with success=True.

First argument should be a translatable message.

If you want the message to be shown as an alert message, specify alert=True.

send_email(self, subject, sender, body, recipients)

Send an email message with the specified arguments (the same signature as django.core.mail.EmailMessage.

recipients is an iterator over a list of strings with email addresses. Any address containing @example.com’ will be removed. Does nothing if the resulting list of recipients is empty.

If body starts with “<”, then it is considered to be HTML.

set_confirm_answer(self, ans)

Set an answer for following confirm in a non-interactive renderer.

confirm(self, ok_func, *msgs, uid=None)

Execute the specified callable ok_func after the user has confirmed the specified message.

The confirmation message may be specified as a series of positional arguments, which will be concatenated to a single prompt.

Pitfall: an action that uses ar.confirm will be called several times, once for each call to confirm(). The full text of the confirmation message must remain the same each time because it serves as the identifier for connecting the two AJAX requests. If the action does changes to the database before its last call to confirm(), it must take care to actually do them only when xcallback_answers is an empty dict.

The callable will be called with a single positional argument, which will be the action request that confirmed the message. In a web context this will be another object than this one.

In a non-interactive renderer (e.g. in a doctest or when using # lino.core.renderer.TestRenderer) the ok_func function (or noop()) is called directly depending on the value of _confirm_answer, which potentially has been set by a previous call to set_confirm_answer().

goto_pk(self, pk, text, **kwargs)

Return a HTML link that navigates to the record with the specified primary key.

When pk is None, returns just the text. The text argument is mandatory.

This is similar to goto_instance(), but is more lightweight (does not do permission checks and no database lookup) and therefore works only in a detail view.

close_window(self, **kw)

Ask client to close the current window. This is the same as BaseRequest.set_response() with close_window=True.

get_data_value(self, obj, name)

Return the value of the virtual field name for this action request on the given object obj.

is_obvious_field(self, name)

Whether the given field is an obvious field in this action request.

For example when you are viewing the partners living in a given city, then the city doesn’t need to be displayed for each partner because that information is “obvious”.

This is used e.g. in customized lino.core.model.Model.as_paragraph() methods.

General rule: in a request on a slave table, the master instance is an obvious value.

get_user(self)

Return the User instance of the user who issued the request. If the authenticated user is acting as somebody else, return that user’s instance.

run(self, ia, *args, **kwargs)

Run the given instance action ia in a child request of this request.

Additional arguments are forwarded to the action. Returns the response of the child request. Does not modify response of parent request.

Usage examples: Write custom actions defines a custom action and then runs it. Voga and The lino_voga.lib.trading plugin use lino_xl.lib.exceprts.Excerpt.do_print to generate a printable document. The demo2 fixture of lino_xl.lib.excerpts does the same (but for generating demo data). Introduction to user management calls lino.modlib.users.User.change_password with arguments.

show(self, spec=None, master_instance=None, column_names=None,
header_level=None, language=None, nosummary=False, stripped=True,
show_links=False, show_urls=False, max_width=None, header_links=False,
display_mode=None, **kwargs)

Show the specified table or action using the current renderer.

The first argument specifies the table or actor to show. It is forwarded to spawn().

If the table is a slave table, then a master_instance must be specified as second argument.

Optional keyword arguments are:

Column_names:

overrides default list of columns

Show_links:

show links and other html formatting. Used .e.g. in User types in Lino Avanti where we want to show whether cells are clickable or not.

Show_urls:

show the real URLs. URLs in doctests are usually replaced by “…” to increase readability. If this is explicitly set to True, Lino prints the full URLs.

Nosummary:

if it is a table with display_mode set to ((None, DISPLAY_MODE_SUMMARY), ), force rendering it as a table.

Display_mode:

override the table’s default display_mode specified by default_display_modes.

Unlike nosummary this can be used to ask a summary for a table that would not show as summary by default. Instead of saying nosummary=True you can say display_mode=DISPLAY_MODE_GRID or display_mode=DISPLAY_MODE_HTML (The display modes DISPLAY_MODE_GRID and DISPLAY_MODE_HTML have the same result in a printed document or in a tested spec).

Header_level:

show also the table header (using specified level)

Header_links:

make column headers clickable so that user can interactively change the sorting order.

Language:

overrides the default language used for headers and translatable data

Any other keyword arguments are forwarded to spawn().

This function either returns a string or prints to stdout and returns None, depending on the current renderer.

Usage in a tested document:

>>> from lino_book.projects.min1.startup import *
>>> rt.login('robin').show('users.UsersOverview', limit=5)
========== ===================== ==========
 Username   User type             Language
---------- --------------------- ----------
 robin      900 (Administrator)   en
 rolf       900 (Administrator)   de
 romain     900 (Administrator)   fr
========== ===================== ==========

Usage in a Jinja template:

{{ar.show('users.UsersOverview')}}
show_story(self, *args, **kwargs)

Shortcut to the renderer’s show_story method.

get_home_url(self, *args, **kw)

Return URL to the “home page” as defined by the renderer, without switching language to default language.

obj2url(self, *args, **kwargs)

Return a url that points to the given database object.

obj2htmls(self, *args, **kwargs)

Like obj2html(), but return a safe html fragment instead of an ElementTree element.

show_menu_path(self, spec, language=None)

Print the menu path of the given actor or action.

This is the replacement for show_menu_path. It has the advantage that it automatically sets the language of the user and that it works for any user type.

row_action_button_ar(self, obj, *args, **kw)

Return an HTML element with a button for running this action request on the given database object. Does not spawn another request.

ar2button(self, *args, **kwargs)

Return an HTML element with a button for running this action request. Does not spawn another request. Does not check permissions.

as_button(self, *args, **kw)

Return a button which when activated executes (a copy of) this request.

instance_action_button(self, ia, *args, **kwargs)

Return an HTML element with a button that would run the given InstanceAction ia on the client.

Maybe deprecated. Use row_action_button() instead.

action_button(self, ba, obj, *args, **kwargs)

Returns the HTML of an action link that will run the specified action.

kwargs may contain additional html attributes like style.

elem2rec_insert(self, ah, elem)

Returns a dict of this record, designed for usage by an InsertWindow.

elem2rec_detailed(ar, elem, with_navinfo=True, **rec)

Adds additional information for this record, used only by detail views.

The “navigation information” is a set of pointers to the next, previous, first and last record relative to this record in this report. (This information can be relatively expensive for records that are towards the end of the queryset. See /blog/2010/0716, /blog/2010/0721, /blog/2010/1116, /blog/2010/1207.)

recno 0 means “the requested element exists but is not contained in the requested queryset”. This can happen after changing the quick filter (search_change) of a detail view.

form2obj_and_save(ar, data, elem, is_new)

Parses the data from HttpRequest to the model instance and saves it.

This is deprecated, but still used by Restful (which is used only by Extensible).

get_help_url(self, docname=None, text=None, **kw)

Generate a link to the help section of the documentation (whose base is defined by lino.core.site.Site.help_url)

Usage example:

help = ar.get_help_url("foo", target='_blank')
msg = _("You have a problem with foo."
        "Please consult %(help)s "
        "or ask your system administrator.")
msg %= dict(help=tostring(help))
kw.update(message=msg, alert=True)
class lino.core.requests.ActionRequest

Represents a full action request, i.e. the context in which an action is running.

Implemented in lino.core.requests and lino.core.tablerequests

renderer

The renderer to use when processing this request.

known_values

A dict of known values used for filtering and when inserting new rows.

is_on_main_actor

Whether this request is on the main actor.

Set this explicitly to False if the JS client should remove certain information when issuing AJAX requests.

Set this explicitly to True if you want Lino to generate permalink URIs instead of javascript URIs. Used e.g. when sending email notifications with actions. Used only by renderers that make a difference (i.e. extjs). See Permalink URIs for details and test coverage.

master_instance

The database object which acts as master. This is None for master requests.

request

The incoming Django HttpRequest object that caused this action request.

gen_insert_button(self, target=None, button_attrs=dict(style='float: right;'), **values)

Generate an insert button using a cached insertable object.

This is functionally equivalent to saying:

if self.insert_action is not None:
    ir = self.insert_action.request_from(ar)
    if ir.get_permission():
        return ir.ar2button()

The difference is that gen_insert_button is more efficient when you do this more than once during a single request.

target is the actor into which we want to insert an object. When this is None, Lino uses self.actor. button_attrs if given, are forwarded to ar2button(). values is a dict of extra default values to apply to the insertable object.

The values must be atomized by the caller, which is especially important when you want to set a foreign key field. So instead of saying:

gen_insert_button(None, user=u)

you must say:

gen_insert_button(None, user=u.pk, userHidden=str(u))

First usage example is in lino_xl.lib.calview. Second usage example is lino_prima.lib.prima.PupilsAndProjects.

override_attrs(self, **kwds)

Context manager for temporarily overriding some attribute. Usage example:

def file2html(self, ar, text, **ctx):
    ...
    with ar.override_attrs(permalink_uris=True):
        ctx.update(href=ar.obj2url(self))
    ...
    return format_html('<a href="{href}"><img src="{src}"/></a>',**ctx)
obj2html(self, obj, text=None, **kwargs)

Return a HTML anchor that opens a detail window on the given database row obj.

The default representation returns the text returned by __str__() in a link that opens the detail window on the given database row.