|Version 2 (modified by 12 years ago) ( diff ),|
Available since: Main Trunk Revision 358+
The main controller function of the RESTful API is:
- shn_rest_controller (defined in models/01_RESTlike_controller.py)
The controller supports various representation formats:
- XML using in-line XSLT transformation to support various XML formats
- JSON for AJAX-style access to resources
This extends the single-table REST Implementation.
A joined resource request is a request to a table ("joined resource" or "component") in dependency of a join to another table ("primary resource" or simply "resource"), e.g.:
- the list of addresses (=component) of a person (=resource).
There are different ways how "Joined Resources" can be seen:
a) as subtables of database tables b) as structured properties of object classes c) as component classes within data compounds
In this implementation, component resources can be joined 1:1 or N:1 to their primary resources, either by natural joins (same key field in both tables) or primary/foreign key matches, where the primary key is always the 'id' field in the primary table.
Example for definition of a joined resource in the model:
resource = 'image' table = module + '_' + resource db.define_table(table, timestamp, uuidstamp, deletion_status, pr_pe_id, opt_pr_image_type, Field('title'), Field('image', 'upload', autodelete=True), Field('description'), Field('comment'), migrate=migrate) # Joined Resource s3xrc.model.add_component(module, resource, multiple=True, joinby='pr_pe_id', deletable=True, editable=True, list_fields = ['id', 'opt_pr_image_type', 'image', 'title','description'])
- module is the name of the module in which the joined resource is defined (prefix)
- resource is the name of the joined resource
- multiple indicates whether this is a 1:N (True) or 1:1 (False) join, defaults to True
- joinby describes the join keys:
- pass a single field name for natural joins (same key field in both tables)
- pass a dictionary of tablename=fieldname pairs for primary/foreign key matching, in which:
- tablename is the name of the respective primary table
- fieldname the name of the foreign key in the joined table that points to the id field in the primary table
joinby = dict(pr_person='person_id')
- fields is a list of the fields in the joined resource that shall appear in list views:
- if omitted or set to None, all readable fields will be included
No definitions are required at the primary resource, just define the table as usual.
def person(): crud.settings.delete_onvalidation = shn_pentity_ondelete return shn_rest_controller(module, 'person', main='first_name', extra='last_name', pheader=shn_pr_pheader, onvalidation=lambda form: shn_pentity_onvalidation(form, table='pr_person', entity_class=1), onaccept=None)
New: the optional pheader argument. This helps you to display some information about the primary resource record in the view while operating on a joined resource (e.g. the person's name and ID, when displaying a list of available images for this person). You may pass static content, or a function or lambda to produce content, which is to be forwarded as pheader variable to the view.
If you pass a function or lambda, it has to take 5 arguments:
- resource = name of the primary resource
- record_id = id of the primary resource record
- representation = data format of the request
- next=None = backlink URL to reproduce the request (with empty method)
- same=None = backlink URL to reproduce the request (with empty method and containing the string '[id]' instead of the primary resource record id)
These backlinks can be used to reproduce the original request after doing something on the primary resource (e.g., edit or change the selected record).
- NOTE: Callbacks from CRUD settings (defined as in the example above) as well as onvalidation and onaccept callbacks are only invoked at requests on the main resource, but not at joined requests. To invoke on Joined Requests, need to define in the
jrlayer.add_jresource()or later using
There are some options which can be set before invoking the REST controller:
def kit(): "RESTlike CRUD controller" response.s3.pdf = URL(r=request, f='kit_export_pdf') response.s3.xls = URL(r=request, f='kit_export_xls') if len(request.args) == 2: crud.settings.update_next = URL(r=request, f='kit_item', args=request.args) return shn_rest_controller(module, 'kit', main='code', onaccept=lambda form: kit_total(form))
response.s3.xls provide the
view/formats.html with an alternate URL to provide a customised version of the PDF/XLS output available when clicking on the icon (
response.s3.rss is also available).
def report_overdue(): "Report on Overdue Invoices - those unpaid 30 days after receipt" response.title = T('Overdue Invoices') overdue = datetime.date.today() - timedelta(days=30) response.s3.filter = (db.fin_invoice.date_out==None) & (db.fin_invoice.date_in < overdue) s3.crud_strings.fin_invoice.title_list = response.title s3.crud_strings.fin_invoice.msg_list_empty = T('No Invoices currently overdue') return shn_rest_controller(module, 'invoice', deletable=False, listadd=False)
response.s3.filter provides a filter which is used in the list view to show the desired subset of records (note that the s3.crud_strings can also be customised - when done in the Controller like this, they are good for just this request).
The argument list is interpreted as follows:
- empty argument list is a LIST attempt to the primary resource
- <id> is a READ attempt on the record #<id> of the primary resource
- <method> is a <method> attempt on the primary resource
- <method>/<id> is a <method> attempt on the record #<id> of the primary resource
- <id>/<joined_resource> is a LIST attempt to the joined resource for the record #<id> of the primary resource
- <joined_resource>?id_label=XXX is a LIST attempt to the joined resource for the record of the primary resource with that label
- <id>/<joined_resource>/<method> is a <method> attempt on the joined resource for the record #<id> of the primary resource
- <joined_resource>/<method>?id_label=XXX analogous.
You may even pass the record ID of the joined resource at the end of the arguments list to access a particular record - which would produce an error message if these two records do not belong together.
The data format of the request can be passed:
- as extension to the primary resource, e.g. http://localhost:8000/sahana/pr/person.xml/1
- as extension to the joined resource, e.g. http://localhost:8000/sahana/pr/person/1/address.xml
- as variable "format", e.g. http://localhost:8000/sahana/pr/person/1/address?format=xml
Policy: "?format=" overrides joined resource extension overrides resource extension
Plug-In Resource Actions
You may plug in custom resource actions to shn_rest_controller, e.g. if you have a custom search function for a resource.
Example: This adds a search_simple method to the person resource, which calls the shn_pr_person_search_simple function:
# Plug into REST controller jrlayer.set_method(module, 'person', None, None, 'search_simple', shn_pr_person_search_simple )
Arguments of jrlayer.set_method:
- module = name of the module of the primary resource
- resource = name of the primary resource
- jmodule = name of the module of the joined resource (if any, maybe None)
- jresource = name of the joined resource (if any, maybe None)
- method = name of the method
- action = the function or lambda to invoke for that method (to remove a plug-in action, just pass None here)
The action method in turn has to take plenty of arguments: