Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More
lino.core.requests¶
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.
>>> from lino_book.projects.noi2.startup import *
Overview¶
As an application developer you see action requests e.g. as an argument to
methods you override, conventionally it is called ar.
An action request
holds information about an incoming web request, e.g.
ar.get_userprovides methods for responding to the client, e.g.
ar.confirm
An ActionRequest is also a BaseRequest and inherits its methods.
An ActionRequest is instantiated from different shortcut methods:
lino.ui.actor.Actor.request()
lino.core.actions.action.Action.request()
The BaseRequest class¶
- class lino.core.requests.base.BaseRequest¶
The return value of
rt.login()is a basic request.Inherits from
lino.core.scp.SiteConfigPointer. Base class forActionRequest.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:
master is ContentType
master is some abstract model
master is not a subclass of Model, e.g.
lino_xl.lib.polls.AnswersByResponse, a virtual table that definesget_row_by_pk.
- 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
BoundActioninstanceanother 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_rowsto 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: <dl> inside <text:p>
- 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.confirmwill be called several times, once for each call toconfirm(). 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 toconfirm(), it must take care to actually do them only whenxcallback_answersis 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 (ornoop()) is called directly depending on the value of_confirm_answer, which potentially has been set by a previous call toset_confirm_answer().
- goto_instance(self, obj, detail_action=None, **kwargs)¶
Add instruction to the
responsethat asks the client to display a detail window on the given database row.Raises a warning “No permission to view {}” when the user has no permission to view the detail window. When the end user sees this warning, they still cannot do anything about it but at least they have better information for their error report.
- 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.db.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
Userinstance 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_printto generate a printable document. Thedemo2fixture oflino_xl.lib.excerptsdoes the same (but for generating demo data). Introduction to user management callslino.modlib.users.User.change_passwordwith 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_modeset 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:
>>> rt.login('robin').show('users.ListedUsers', limit=5) ========== ===================== ========== Username User type Language ---------- --------------------- ---------- andy 100 (Customer) en bert 900 (Administrator) en chloe 100 (Customer) en jean 400 (Developer) en luc 400 (Developer) en ========== ===================== ==========
Usage in a Jinja template:
{{ar.show('users.ListedUsers')}}
- show_story(self, *args, **kwargs)¶
Shortcut to the renderer’s
show_storymethod.
- get_home_url(self, **kwargs)¶
Return URL to the Home page.
The return value depends on where the renderer is mounted. In noi2 it is located under /admin, as defined in the site’s
web_front_ends.>>> ar = rt.login() >>> ar.get_home_url() '/admin' >>> dd.plugins.publisher.renderer.get_home_url(ar) '/'
You may explicitly specify another language using the keyword ul (the URL abbreviation for “user language” which is defined in
lino.core.constants):>>> constants.URL_PARAM_USER_LANGUAGE 'ul'
Since 20260521 this function no longer accepts positional arguments.
- 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.
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
InstanceActioniaon 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.
kwargsmay 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.ActionRequest¶
Represents a full action request, i.e. the context in which an action is running.
Implemented in
lino.core.requestsandlino.core.tablerequests- execute()¶
This will actually call the
get_data_iterator()and run the database query.Automatically called when either
data_iteratororsliced_data_iteratoris accesed.
- get_total_count()¶
Return the number of rows.
When actor is not a table, we assume that there is one row. This is used e.g. when courses.StatusReport is shown in the the dashboard. A Report must return 1 because otherwise the dashboard believes it is empty.
Calling len() on a QuerySet would execute the whole SELECT. See /blog/2012/0124
- create_instance()¶
Create and return a database row using the context information of this action request (
create_kwandknown_values) and the optionally specified keyword arguments.This calls
lino.ui.actor.Actor.create_instance().
- renderer¶
The renderer to use when processing this request.
- create_kw¶
A dictionary with keywords to use in
create_instance().I gets filled from
lino.core.actor.Actor.get_filter_kw().If this is None, it means that no database rows can be created using this action 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.
- permalink_uris¶
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 toar2button(). 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 islino_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.
Utilities¶
- class lino.core.requests.utils.ValidActionResponses¶
These are the allowed keyword arguments for
ar.set_response, and the action responses supported byLino.handle_action_result()(defined inlinolib.js).This class is never instantiated, but used as a placeholder for these names and their documentation.
- message¶
A translatable message text to be shown to the user.
- alert¶
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).
- success¶
True when actio executed successfully.
- alert_eval_js¶
Javascript code to be evaluated after the confirmation of the alert dialog.
- rows¶
An iterable of database objects that will be serialized as a list.
- title¶
The dynamic title to give to the window or component that shows this response. TODO: is this still being used?
- count¶
The number of rows in a list response.
- data_record¶
Certain requests are expected to return detailed information about a single data record. That’s done in
data_recordwhich 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¶
When an action returns a record_id, it asks the user interface to jump to the given record.
- refresh_delayed_value¶
A string referencing an actor_id corresponding to a DelayedValue equivalent element or boolean True meaning all the DelayedValue(s) should be refreshed.
- xcallback¶
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¶
Leave current page and go to the given URL.
In react, this works within the URLContext object (within the hash router context but NOT in browser native location object) where url must match the route “/api/:packId/:actorId/:pk?/:fieldName?” or “/”
- open_url¶
Open the given URL in a new browser window.
- replace_url¶
Open the given URL in the current browser window overriding the current url.
In react, unlike goto_url this overrides the browser native location object (sets href on it).
- eval_js¶
Javascript to be executed by the client.
- detail_handler_name¶
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().
- reset_frontend¶
Specifies whether to reset the state of the whole app.