Welcome | Get started | Dive into Lino | Contribute | Topics | Reference | More

lino.core.requests

See introduction in Using action requests.

Functions

bool2text(x)

noop(ar)

Classes

ActionRequest([actor, unused_request, ...])

Holds information about an individual web request and provides methods like

BaseRequest([request, parent, hash_router, ...])

Base class of all action requests.

InstanceAction(action, actor, instance, owner)

Volatile object that wraps a given action to be run on a given model instance.

PhantomRow(request, **kw)

StringLogger(parent, level)

ValidActionResponses()

These are the allowed keyword arguments for ar.set_response, and the action responses supported by Lino.handle_action_result() (defined in linolib.js).

VirtualRow(**kw)

class lino.core.requests.ValidActionResponses

Bases: object

These are the allowed keyword arguments for ar.set_response, and the action responses supported by Lino.handle_action_result() (defined in linolib.js).

This class is never instantiated, but used as a placeholder for these names and their documentation.

message = None

A translatable message text to be shown to the user.

alert = None

Set this to some translatable text to specify that the message is rather important and should alert and should be presented in a dialog box to be confirmed by the user. The text is used as the title of the alert box. If you specify True, then Lino uses a default text like "Alert" or "Warning" (depending on context).

alert_eval_js = None

Javascript code to be evaluated after the confirmation of the alert dialog.

rows = None

An iterable of database objects that will be serialized as a list.

title = None

The dynamic title to give to the window or component which shows this response. TODO: is this still being used?

count = None

The number of rows in a list response.

data_record = None

Certain requests are expected to return detailed information about a single data record. That's done in data_record which must itself be a dict with the following keys:

  • id : the primary key of this record_deleted

  • title : the title of the detail window

  • data : a dict with one key for every data element

  • navinfo : an object with information for the navigator

  • disable_delete : either null (if that record may be deleted, or otherwise a message explaining why.

record_id = None

When an action returns a record_id, it asks the user interface to jump to the given record.

refresh_delayed_value = None

A string referencing an actor_id corresponding to a DelayedValue equivalent element or boolean True meaning all the DelayedValue(s) should be refreshed.

xcallback = None

Used for dialogs asking simple yes/no/later style questions. Includes all the data the client needs in order to send the same action request again, but with some extra confirmation values.

Is a dict which includes the following values:

  • actor_id : The id of the actor

  • an : The action name of the action which was run

  • sr : List of selected values

goto_url = None

Leave current page and go to the given URL.

open_url = None

Open the given URL in a new browser window.

warning_message = None

deprecated

detail_handler_name = None

The name of the detail handler to be used. Application code should not need to use this. It is automatically set by ActorRequest.goto_instance().

class lino.core.requests.BaseRequest(request=None, parent=None, hash_router=None, is_on_main_actor=True, permalink_uris=None, **kw)

Bases: object

Base class of all action requests.

An action request represents the context in which an action is running.

renderer = None

The renderer to use when processing this request.

known_values = {}

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

master_instance = None

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

request = None

The incoming Django HttpRequest object that caused this action request.

is_on_main_actor = True

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.

parse_req(request, rqdata, **kw)

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

setup_from(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(**kw)

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

spawn(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(**kw)

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

set_selected_pks(*selected_pks)

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

The special pks's -99998 and -99999 are filtered out.

get_permission()

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(**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(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(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(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(ans)

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

confirm(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(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(**kw)

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

get_total_count()

TableRequest overrides this to return the number of rows.

For other requests we assume that there is one row. This is used e.g. when courses.StatusReport is shown in the the dashboard. A Report returns always 1 because otherwise the dashboard believes it is empty.

get_data_value(obj, name)

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

get_user()

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(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). User management à la Lino calls lino.modlib.users.User.change_password with arguments.

story2html(story, *args, **kwargs)

Convert a story into a stream of HTML elements.

show(spec=None, master_instance=None, column_names=None, header_level=None, language=None, nosummary=False, stripped=True, show_links=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.

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

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=((None, DISPLAY_MODE_TABLE), ) or display_mode=((None, DISPLAY_MODE_HTML), ) (The display modes DISPLAY_MODE_TABLE 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().

Note that 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.api import rt
>>> rt.login('robin').show('users.UsersOverview', limit=5)

Usage in a Jinja template:

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

Shortcut to the renderer's show_story method.

get_home_url(*args, **kw)

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

is_obvious_field(name)

Return True if the given field is "obvious" in the context of this action request.

For example when you are viewing the partners living in a given city, then the city field is "obvious" and doesn't need to be displayed for each partner.

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

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

obj2url(*args, **kwargs)

Return a url that points to the given database object.

obj2html(obj, text=None, **kwargs)

Return a HTML element that points to a detail view of the given database object. Depending on the renderer this will be more or less clickable.

obj2htmls(*args, **kwargs)

Return a safe html fragment that points to the given database object.

Adds a detail link when there is a detail view and when the text does not yet contain html.

This is rather for internal use to make the items in DISPLAY_MODE_LIST clickable when needed.

Compare the following use cases:

lino.modlib.users.UsersOverview, lino_xl.lib.working.WorkedHours, lino_xl.lib.contacts.RolesByCompany and lino_xl.lib.contacts.RolesByPerson

menu_item_button(*args, **kwargs)

Forwards to lino.core.renderer.()

show_menu_path(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(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(*args, **kwargs)

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

instance_action_button(ia, *args, **kwargs)

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

action_button(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.

as_button(*args, **kw)

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

elem2rec_insert(ah, elem)

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

elem2rec_detailed(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(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(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(actor=None, unused_request=None, action=None, unused_renderer=None, rqdata=None, **kw)

Bases: BaseRequest

Holds information about an individual web request and provides methods like

  • get_user

  • confirm

  • spawn

An ActionRequest is also a BaseRequest and inherits its methods.

An ActionRequest is instantiated from different shortcut methods:

create_instance(**kw)

Create a row (a model instance if this is a database table) using the specified keyword arguments.

get_status(**kw)

Return a dict with the "status", i.e. a json representation of this request.

clear_cached_status()

Remove any previously computed status information.

The status information of a request is cached to avoid performance issues e.g. in calendar views where a many buttons can be rendered for a same request and where the status information can be relatively heavy.

But sometimes you don't want this. In that case you call clear_cached_status().

run(*args, **kw)

Runs this action request.

class lino.core.requests.InstanceAction(action, actor, instance, owner)

Bases: object

Volatile object that wraps a given action to be run on a given model instance.

bound_action

The bound action that will run.

instance

The database object on which the action will run.

owner
run_from_code(ar, *args, **kw)

Probably to be deprecated. Run this action on this instance in the given session, updating the response of the session. Returns the return value of the action.

run_from_ui(ar, *args, **kwargs)

Run this action on this instance in the given session, updating the response of the session. Returns nothing.

request_from(ses, **kwargs)

Create an action request on this instance action without running the action.

run_from_session(ses, **kwargs)

Run this instance action in a child request of given session.

Additional arguments are forwarded to the action. Returns the response of the child request. Doesn't modify response of parent request.

as_button(*args, **kwargs)

Return a HTML chunk with a "button" which, when clicked, will execute this action on this instance. This is being used in the The Lino Polls tutorial.