desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Helper function to parse a string into a date, time or datetime value (always returns UTC datetimes). @param dtstr: the string @param field_type: the field type'
@staticmethod def _dtparse(dtstr, field_type='datetime'):
error = None value = None try: dt = s3_decode_iso_datetime(str(dtstr)) value = s3_utc(dt) except: error = sys.exc_info()[1] if (error is None): if (field_type == 'date'): value = value.date() elif (field_type == 'time'): value = value.t...
'Creates a record (Storage) from a <resource> element and validates it @param table: the database table @param element: the element @param original: the original record @param files: dict of attached upload files @param postprocess: post-process hook (xml_post_parse) @param skip: fields to skip'
@classmethod def record(cls, table, element, original=None, files=None, skip=[], postprocess=None):
valid = True record = Storage() db = current.db auth = current.auth utable = auth.settings.table_user gtable = auth.settings.table_group UID = cls.UID uid = None if ((UID in table.fields) and (UID not in skip)): uid = current.xml.import_uid(element.get(UID, None)) if ...
'Get options of a field as <select> @param table: the Table @param fieldname: the Field name @param parent: the parent element in the tree @param show_uids: include UUIDs in foreign key options @param hierarchy: include parent ID in foreign key options (if the lookup table is hierarchical)'
@classmethod def get_field_options(cls, table, fieldname, parent=None, show_uids=False, hierarchy=False):
options = None try: field = table[fieldname] except (KeyError, AttributeError): pass else: requires = field.requires if requires: if (not isinstance(requires, (list, tuple))): requires = [requires] requires = requires[0] ...
'Get options of option fields in a table as <select>s @param prefix: the application prefix @param name: the resource name (without prefix) @param fields: optional list of fieldnames @param show_uids: include UIDs in foreign key options @param hierarchy: include parent IDs in foreign key options (if the lookup table is...
def get_options(self, table, fields=None, show_uids=False, hierarchy=False):
if fields: if (not isinstance(fields, (list, tuple, set))): fields = [fields] if (len(fields) == 1): return self.get_field_options(table, fields[0], show_uids=show_uids, hierarchy=hierarchy) options = etree.Element(self.TAG.options) if table: options.set(self....
'Get fields in a table as <fields> element @param prefix: the application prefix @param name: the resource name (without prefix) @param parent: the parent element to append the tree to @param options: include option lists in option fields @param references: include option lists even in reference fields'
def get_fields(self, prefix, name, parent=None, meta=False, options=False, references=False, labels=False):
db = current.db tablename = ('%s_%s' % (prefix, name)) table = db.get(tablename, None) if (parent is not None): fields = parent else: fields = etree.Element(self.TAG.fields) if table: ATTRIBUTE = self.ATTRIBUTE if (parent is None): fields.set(ATTRIBUTE...
'Get the table structure as XML tree @param prefix: the application prefix @param name: the tablename (without prefix) @param parent: the parent element to append the tree to @param options: include option lists in option fields @param references: include option lists even in reference fields @raise AttributeError: in ...
def get_struct(self, prefix, name, alias=None, parent=None, meta=False, options=True, references=False):
db = current.db tablename = ('%s_%s' % (prefix, name)) table = db.get(tablename, None) if (table is not None): if (parent is not None): e = etree.SubElement(parent, self.TAG.resource) else: e = etree.Element(self.TAG.resource) e.set(self.ATTRIBUTE.name, ta...
'Converts a data field from JSON into an element @param key: key (field name) @param value: value for the field @param native: use native mode @type native: bool'
@classmethod def __json2element(cls, key, value, native=False):
if isinstance(value, dict): element = cls.__obj2element(key, value, native=native) elif isinstance(value, (list, tuple)): if (key != cls.TAG.item): element = etree.Element(key) else: element = etree.Element(cls.TAG.list) json2element = cls.__json2element ...
'Converts a JSON object into an element @param tag: tag name for the element @param obj: the JSON object @param native: use native mode for attributes'
@classmethod def __obj2element(cls, tag, obj, native=False):
resource = field = None if (not tag): tag = cls.TAG.object elif native: if tag.startswith(cls.PREFIX.reference): field = tag[(len(cls.PREFIX.reference) + 1):] tag = cls.TAG.reference elif tag.startswith(cls.PREFIX.options): resource = tag[(len(cls....
'Converts JSON into an element tree @param source: the JSON source @param format: name of the XML root element'
@classmethod def json2tree(cls, source, format=None):
try: root_dict = json.load(source) except (ValueError,): e = sys.exc_info()[1] raise HTTP(400, body=cls.json_message(False, 400, e)) native = False if (not format): format = cls.TAG.root native = True if (root_dict and isinstance(root_dict, dict)): roo...
'Converts an element into JSON @param element: the element @param native: use native mode for attributes'
@classmethod def __element2json(cls, element, native=False):
TAG = cls.TAG ATTRIBUTE = cls.ATTRIBUTE PREFIX = cls.PREFIX element2json = cls.__element2json if (element.tag == TAG.list): obj = [] append = obj.append for child in element: tag = child.tag if (not isinstance(tag, basestring)): continu...
'Converts an element tree into JSON @param tree: the element tree @param pretty_print: indent and insert line breaks into the JSON string to make it human-readable (useful for debug) @param native: tree is S3XML @param as_dict: return a JSON-serializable object instead of a string, useful for embedding the data in othe...
@classmethod def tree2json(cls, tree, pretty_print=False, native=False, as_dict=False):
if isinstance(tree, etree._ElementTree): root = tree.getroot() else: root = tree if (native or (root.tag == cls.TAG.root)): native = True else: native = False root_dict = cls.__element2json(root, native=native) if ('s3' in root_dict): if (root_dict['s3'] =...
'Collect errors from an error tree @param job: the import job, resource or error tree as Element'
@staticmethod def collect_errors(job):
errors = [] try: if isinstance(job, etree._Element): error_tree = job else: error_tree = job.error_tree except AttributeError: return errors if (error_tree is None): return errors elements = error_tree.xpath('.//*[@error]') for element in e...
'Convert a table in an XLS (MS Excel) sheet into an ElementTree, consisting of <table name="format">, <row> and <col field="fieldname"> elements (see: L{csv2tree}). The returned ElementTree can be imported using S3CSV stylesheets (through S3Resource.import_xml()). @param source: the XLS source (stream, or XLRD book, or...
@classmethod def xls2tree(cls, source, resourcename=None, extra_data=None, hashtags=None, sheet=None, rows=None, cols=None, fields=None, header_row=True):
import xlrd ATTRIBUTE = cls.ATTRIBUTE FIELD = ATTRIBUTE.field HASHTAG = ATTRIBUTE.hashtag TAG = cls.TAG COL = TAG.col SubElement = etree.SubElement DEFAULT_SHEET_NAME = 'SahanaData' root = etree.Element(TAG.table) if (resourcename is not None): root.set(ATTRIBUTE.name, re...
'Convert a table-form CSV source into an element tree, consisting of <table name="format">, <row> and <col field="fieldname"> elements. @param source: the source (file-like object) @param resourcename: the resource name @param extra_data: dict of extra cols {key:value} to add to each row @param hashtags: dict of hashta...
@classmethod def csv2tree(cls, source, resourcename=None, extra_data=None, hashtags=None, delimiter=',', quotechar='"'):
import csv csv.field_size_limit(((2 ** 20) * 100)) ATTRIBUTE = cls.ATTRIBUTE FIELD = ATTRIBUTE.field HASHTAG = ATTRIBUTE.hashtag TAG = cls.TAG COL = TAG.col SubElement = etree.SubElement root = etree.Element(TAG.table) if (resourcename is not None): root.set(ATTRIBUTE.nam...
'Constructor @param stylesheet: the stylesheet (pathname or stream)'
def __init__(self, stylesheet):
self.tree = current.xml.parse(stylesheet) if (not self.tree): current.log.error(('%s parse error: %s' % (stylesheet, current.xml.error))) self.select = None self.skip = None
'Get the fields to include/exclude for the specified table. @param tablename: the tablename @return: tuple of lists (include, exclude) of fields to include or exclude. None indicates "all fields", whereas an empty list indicates "no fields".'
def get_fields(self, tablename):
ANY = 'ANY' default = (None, None) tree = self.tree if (not tree): return default if (self.select is None): self.__inspect() def find_match(items, tablename, default): if (tablename in items): match = items[tablename] else: match = False ...
'Check the fields configuration in the stylesheet (if any)'
def __inspect(self):
ALL = 'ALL' ANY = 'ANY' tree = self.tree ns = {'s3': 'http://eden.sahanafoundation.org/wiki/S3'} elements = tree.xpath('./s3:fields', namespaces=ns) select = {} skip = {} for element in elements: tables = element.get('tables', ANY).split(',') fields = element.get('select'...
'Transform an element tree using this format @param tree: the element tree @param args: parameters for the stylesheet'
def transform(self, tree, **args):
if (not self.tree): current.log.error('XMLFormat: no stylesheet available') return tree return current.xml.transform(tree, self.tree, **args)
'Constructor to define the form and its elements. @param elements: the form elements @param attributes: form attributes'
def __init__(self, *elements, **attributes):
self.elements = [] append = self.elements.append debug = current.deployment_settings.get_base_debug() for element in elements: if (not element): continue if isinstance(element, S3SQLFormElement): append(element) elif isinstance(element, str): a...
'Render/process the form. To be implemented in subclass. @param request: the S3Request @param resource: the target S3Resource @param record_id: the record ID @param readonly: render the form read-only @param message: message upon successful form submission @param format: data format extension (for audit) @param options...
def __call__(self, request=None, resource=None, record_id=None, readonly=False, message='Record created/updated', format=None, **options):
return None
'Support len(crud_form)'
def __len__(self):
return len(self.elements)
'Get a configuration setting for the current table @param key: the setting key @param default: fallback value if the setting is not available'
def _config(self, key, default=None):
tablename = self.tablename if tablename: return current.s3db.get_config(tablename, key, default) else: return default
'Render submit buttons @param readonly: render the form read-only @return: list of submit buttons'
@staticmethod def _submit_buttons(readonly=False):
T = current.T s3 = current.response.s3 settings = s3.crud if settings.custom_submit: submit = [(None, settings.submit_button, settings.submit_style)] submit.extend(settings.custom_submit) buttons = [] for (name, label, _class) in submit: if isinstance(label, b...
'Insert dummy fields into forms - these are simple DIVs placed into the correct place in the form which are meant to be acted upon by custom JavaScript routines @param form: the form @param formstyle: the formstyle @param dummy_fields:'
@staticmethod def _insert_dummy_fields(form, formstyle, dummy_fields):
if (not dummy_fields): return
'Insert subheadings into forms @param form: the form @param tablename: the tablename @param formstyle: the formstyle @param subheadings: OLD (maintained for backwards compatibility): a dict of {"Header": Fieldnames}, where Fieldname can be either a single field name or a list/tuple of field names belonging under that h...
@staticmethod def _insert_subheadings(form, tablename, formstyle, subheadings):
if (not subheadings): return if (tablename in subheadings): subheadings = subheadings.get(tablename) if (formstyle.__name__ in ('formstyle_table', 'formstyle_table_inline')): def create_subheading(represent, tablename, f): return TR(TD(represent, _colspan=3, _class='subhe...
'Render/process the form. @param request: the S3Request @param resource: the target S3Resource @param record_id: the record ID @param readonly: render the form read-only @param message: message upon successful form submission @param format: data format extension (for audit) @param options: keyword options for the form ...
def __call__(self, request=None, resource=None, record_id=None, readonly=False, message='Record created/updated', format=None, **options):
if (resource is None): self.resource = request.resource (self.prefix, self.name, self.table, self.tablename) = request.target() else: self.resource = resource self.prefix = resource.prefix self.name = resource.name self.tablename = resource.tablename self....
'Pre-populate the form with values from a previous record or controller-submitted data @param from_table: the table to copy the data from @param from_record: the record to copy the data from @param map_fields: field selection/mapping @param data: the data to prepopulate the form with @param format: the request format e...
def prepopulate(self, from_table=None, from_record=None, map_fields=None, data=None, format=None):
table = self.table record = None if (from_table is not None): if map_fields: if isinstance(map_fields, dict): fields = [from_table[map_fields[f]] for f in map_fields if ((f in table.fields) and (map_fields[f] in from_table.fields) and table[f].writable)] elif ...
'Change to update if this request attempts to create a duplicate entry in a link table @param request: the request @param record_id: the record ID'
def deduplicate_link(self, request, record_id):
linked = self.resource.linked table = self.table session = current.session if ((request.env.request_method == 'POST') and (linked is not None)): pkey = table._id.name post_vars = request.post_vars if (not post_vars[pkey]): lkey = linked.lkey rkey = linked....
'Process the form @param form: FORM instance @param vars: request POST variables @param onvalidation: callback(function) upon successful form validation @param onaccept: callback(function) upon successful form acceptance @param hierarchy: the data for the hierarchy link to create @param link: component link @param http...
def process(self, form, vars, onvalidation=None, onaccept=None, hierarchy=None, link=None, http='POST', format=None):
table = self.table tablename = self.tablename if isinstance(onvalidation, dict): onvalidation = onvalidation.get(tablename, []) if (link and link.postprocess): postprocess = link.postprocess if isinstance(onvalidation, list): onvalidation.insert(0, postprocess) ...
'S.insert(index, object) -- insert object before index'
def insert(self, index, element):
if (not element): return if isinstance(element, S3SQLFormElement): self.elements.insert(index, element) elif isinstance(element, str): self.elements.insert(index, S3SQLField(element)) elif isinstance(element, tuple): l = len(element) if (l > 1): (label...
'S.append(object) -- append object to the end of the sequence'
def append(self, element):
self.insert(len(self), element)
'Render/process the form. @param request: the S3Request @param resource: the target S3Resource @param record_id: the record ID @param readonly: render the form read-only @param message: message upon successful form submission @param format: data format extension (for audit) @param options: keyword options for the form ...
def __call__(self, request=None, resource=None, record_id=None, readonly=False, message='Record created/updated', format=None, **options):
db = current.db response = current.response s3 = response.s3 if (resource is None): resource = request.resource (self.prefix, self.name, self.table, self.tablename) = request.target() else: self.prefix = resource.prefix self.name = resource.name self.tablename...
'Run the onvalidation callbacks for the master table and all subtables in the form, and store any errors in the form. @param form: the form'
def validate(self, form):
s3db = current.s3db config = self._config if self.record_id: onvalidation = config('update_onvalidation', config('onvalidation', None)) else: onvalidation = config('create_onvalidation', config('onvalidation', None)) if (onvalidation is not None): try: callback(on...
'Create/update all records from the form. @param form: the form @param format: data format extension (for audit) @param link: resource.link for linktable components @param hierarchy: the data for the hierarchy link to create @param undelete: reinstate a previously deleted record'
def accept(self, form, format=None, link=None, hierarchy=None, undelete=False):
db = current.db table = self.table main_data = self._extract(form) (master_id, master_form_vars) = self._accept(self.record_id, main_data, format=format, link=link, hierarchy=hierarchy, undelete=undelete) if (not master_id): return else: main_data[table._id.name] = master_id ...
'Extract data for a subtable from the form @param form: the form @param alias: the component alias of the subtable'
def _extract(self, form, alias=None):
if (alias is None): return self.table._filter_fields(form.vars) else: subform = Storage() alias_length = len(alias) form_vars = form.vars for k in form_vars: if ((k[:4] == 'sub_') and (k[4:((4 + alias_length) + 1)] == ('%s_' % alias))): fn = k[...
'Create or update a record @param record_id: the record ID @param data: the data @param alias: the component alias @param format: the request format (for audit) @param hierarchy: the data for the hierarchy link to create @param link: resource.link for linktable components @param undelete: reinstate a previously deleted...
def _accept(self, record_id, data, alias=None, format=None, hierarchy=None, link=None, undelete=False):
if (alias is not None): if ((not data) or ((not record_id) and all(((value is None) for value in data.values())))): return (None, Storage()) elif (record_id and (not data)): return (record_id, Storage()) s3db = current.s3db if (alias is None): component = self.resourc...
'Constructor to define the form element, to be extended in subclass. @param selector: the data object selector @param options: options for the form element'
def __init__(self, selector, **options):
self.selector = selector self.options = Storage(options)
'Method to resolve this form element against the calling resource. To be implemented in subclass. @param resource: the resource @return: a tuple form element, original field name, Field instance for the form renderer The form element can be None for the main table, the component alias for a subtable, or this form eleme...
def resolve(self, resource):
return (None, None, None)
'Rename a field (actually: create a new Field instance with the same attributes as the given Field, but a different field name). @param field: the original Field instance @param name: the new name @param comments: render comments - if set to False, only navigation items with an inline() renderer method will be rendered...
@staticmethod def _rename_field(field, name, comments=True, popup=None, skip_post_validation=False, label=DEFAULT, widget=DEFAULT):
if (not hasattr(field, 'type')): field = Storage(comment=None, type='string', length=255, unique=False, uploadfolder=None, autodelete=False, label='', writable=False, readable=True, default=None, update=None, compute=None, represent=(lambda v: (v or ''))) requires = None required = False ...
'Method to resolve this form element against the calling resource. @param resource: the resource @return: a tuple subtable alias (or None for main table), original field name, Field instance for the form renderer'
def resolve(self, resource):
from s3query import S3ResourceField rfield = S3ResourceField(resource, self.selector) field = rfield.field if (field is None): raise SyntaxError(('Invalid selector: %s' % self.selector)) tname = rfield.tname options = self.options label = options.get('label', DEFAULT) widge...
'Method to resolve this form element against the calling resource. @param resource: the resource @return: a tuple subtable alias (or None for main table), original field name, Field instance for the form renderer'
def resolve(self, resource):
field = Field(self.selector, label='', widget=self) return (self, None, field)
'Widget renderer for the input field. To be implemented in subclass (if required) and to be set as widget=self for the field returned by the resolve()-method of this form element. @param field: the input field @param value: the value to populate the widget @param attributes: attributes for the widget @return: the widge...
def __call__(self, field, value, **attributes):
return DIV(_class='s3-dummy-field')
'Initialize this form element for a particular record. This method will be called by the form renderer to populate the form for an existing record. To be implemented in subclass. @param resource: the resource the record belongs to @param record_id: the record ID @return: the value for the input field that corresponds t...
def extract(self, resource, record_id):
return None
'Validator method for the input field, used to extract the data from the input field and prepare them for further processing by the accept()-method. To be implemented in subclass and set as requires=self.parse for the input field in the resolve()-method of this form element. @param value: the value returned from the in...
def parse(self, value):
return (value, None)
'Widget renderer for the input field. To be implemented in subclass (if required) and to be set as widget=self for the field returned by the resolve()-method of this form element. @param field: the input field @param value: the value to populate the widget @param attributes: attributes for the widget @return: the widge...
def __call__(self, field, value, **attributes):
raise NotImplementedError
'Read-only representation of this form element. This will be used instead of the __call__() method when the form element is to be rendered read-only. @param value: the value as returned from extract() @return: the read-only representation of this element as string or HTML helper'
def represent(self, value):
return ''
'Post-process this form element and perform the related transactions. This method will be called after the main form has been accepted, where the master record ID will be provided. @param form: the form @param master_id: the master record ID @param format: the data format extension @return: True on success, False on er...
def accept(self, form, master_id=None, format=None):
return True
'Constructor, used like: field.requires = SKIP_POST_VALIDATION(field.requires) @param other: the actual field validator'
def __init__(self, other=None):
if (other and isinstance(other, (list, tuple))): other = other[0] self.other = other if other: if hasattr(other, 'multiple'): self.multiple = other.multiple if hasattr(other, 'options'): self.options = other.options if hasattr(other, 'formatter'): ...
'Validation @param value: the value'
def __call__(self, value):
other = self.other if ((current.request.env.request_method == 'POST') or (not other)): return (value, None) if (not isinstance(other, (list, tuple))): other = [other] for r in other: (value, error) = r(value) if error: return (value, error) return (value, ...
'Constructor'
def __init__(self):
self.inject_script() self.columns = None self.row_actions = True
'Set column widths for inline-widgets, can be used by subclasses to render CSS classes for grid-width @param columns: iterable of column widths @param actions: whether the subform contains an action column'
def set_columns(self, columns, row_actions=True):
self.columns = columns self.row_actions = row_actions
'Outer container for the subform @param data: the data dict (as returned from extract()) @param item_rows: the item rows @param action_rows: the (hidden) action rows @param empty: no data in this component @param readonly: render read-only'
def subform(self, data, item_rows, action_rows, empty=False, readonly=False):
if empty: subform = current.T('No entries currently available') else: headers = self.headers(data, readonly=readonly) subform = TABLE(headers, TBODY(item_rows), TFOOT(action_rows), _class=' '.join(('embeddedComponent', self.layout_class))) return subform
'Render this component read-only (table-style) @param resource: the S3Resource @param data: the data dict (as returned from extract())'
def readonly(self, resource, data):
audit = current.audit (prefix, name) = (resource.prefix, resource.name) xml_decode = current.xml.xml_decode items = data['data'] fields = data['fields'] trs = [] for item in items: if ('_id' in item): record_id = item['_id'] else: continue audi...
'Render this component read-only (list-style) @param resource: the S3Resource @param data: the data dict (as returned from extract())'
@staticmethod def render_list(resource, data):
audit = current.audit (prefix, name) = (resource.prefix, resource.name) xml_decode = current.xml.xml_decode items = data['data'] fields = data['fields'] elements = [] for item in items: if ('_id' in item): record_id = item['_id'] else: continue ...
'Render the header row with field labels @param data: the input field data as Python object @param readonly: whether the form is read-only'
def headers(self, data, readonly=False):
fields = data['fields'] render_header = False header_row = TR(_class='label-row static') happend = header_row.append for f in fields: label = f['label'] if label: render_header = True label = TD(LABEL(label)) happend(label) if render_header: ...
'Render subform row actions into the row @param subform: the subform row @param formname: the form name @param index: the row index @param item: the row data @param readonly: this is a read-row @param editable: this row is editable @param deletable: this row is deletable'
@staticmethod def actions(subform, formname, index, item=None, readonly=True, editable=True, deletable=True):
T = current.T action_id = ('%s-%s' % (formname, index)) def action(title, name, throbber=False): btn = DIV(_id=('%s-%s' % (name, action_id)), _class=('inline-%s' % name)) if throbber: return DIV(btn, DIV(_class='inline-throbber hide', _id=('throbber-%s' % action_id))) ...
'Formstyle for subform read-rows, normally identical to rowstyle, but can be different in certain layouts'
def rowstyle_read(self, form, fields, *args, **kwargs):
return self.rowstyle(form, fields, *args, **kwargs)
'Formstyle for subform action-rows'
def rowstyle(self, form, fields, *args, **kwargs):
def render_col(col_id, label, widget, comment, hidden=False): if (col_id == 'submit_record__row'): if hasattr(widget, 'add_class'): widget.add_class('inline-row-actions') col = TD(widget) elif comment: col = TD(DIV(widget, comment), _id=col_id) ...
'Inject custom JS to render new read-rows'
@staticmethod def inject_script():
return
'Header-row layout: same as default, but non-static (i.e. hiding if there are no visible read-rows, because edit-rows have their own labels)'
def headers(self, data, readonly=False):
headers = super(S3SQLVerticalSubFormLayout, self).headers header_row = headers(data, readonly=readonly) element = header_row.element('tr') if hasattr(element, 'remove_class'): element.remove_class('static') return header_row
'Formstyle for subform read-rows, same as standard horizontal layout.'
def rowstyle_read(self, form, fields, *args, **kwargs):
rowstyle = super(S3SQLVerticalSubFormLayout, self).rowstyle return rowstyle(form, fields, *args, **kwargs)
'Formstyle for subform edit-rows, using a vertical formstyle because multiple fields combined with location-selector are too complex for horizontal layout.'
def rowstyle(self, form, fields, *args, **kwargs):
from s3theme import formstyle_foundation as formstyle if args: col_id = form label = fields (widget, comment) = args hidden = kwargs.get('hidden', False) return formstyle(col_id, label, widget, comment, hidden) else: parent = TD(_colspan=len(fields)) f...
'Method to resolve this form element against the calling resource. @param resource: the resource @return: a tuple (self, None, Field instance)'
def resolve(self, resource):
selector = self.selector if (selector not in resource.components): hook = current.s3db.get_component(resource.tablename, selector) if hook: resource._attach(selector, hook) else: raise SyntaxError(('Undefined component: %s' % selector)) component = resou...
'Initialize this form element for a particular record. Retrieves the component data for this record from the database and converts them into a JSON string to populate the input field with. @param resource: the resource the record belongs to @param record_id: the record ID @return: the JSON for the input field.'
def extract(self, resource, record_id):
self.resource = resource component_name = self.selector if (component_name in resource.components): component = resource.components[component_name] options = self.options if component.link: link = options.get('link', True) if link: component = ...
'Validator method, converts the JSON returned from the input field into a Python object. @param value: the JSON from the input field. @return: tuple of (value, error), where value is the converted JSON, and error the error message if the decoding fails, otherwise None'
def parse(self, value):
if isinstance(value, basestring): try: value = json.loads(value) except: import sys error = sys.exc_info()[1] if hasattr(error, 'message'): error = error.message else: error = None else: value = None ...
'Widget method for this form element. Renders a table with read-rows for existing entries, a variable edit-row to update existing entries, and an add-row to add new entries. This widget uses s3.inline_component.js to facilitate manipulation of the entries. @param field: the Field for this form element @param value: the...
def __call__(self, field, value, **attributes):
options = self.options if (options.readonly is True): return self.represent(value) if (value is None): value = field.default if isinstance(value, basestring): data = json.loads(value) else: data = value value = json.dumps(value, separators=SEPARATORS) if (...
'Read-only representation of this sub-form @param value: the value returned from extract()'
def represent(self, value):
if isinstance(value, basestring): data = json.loads(value) else: data = value if (data['data'] == []): return current.messages['NONE'] resource = self.resource component = resource.components[data['component']] layout = self._layout() columns = self.options.get('colum...
'Post-processes this form element against the POST data of the request, and create/update/delete any related records. @param form: the form @param master_id: the ID of the master record in the form @param format: the data format extension (for audit)'
def accept(self, form, master_id=None, format=None):
fname = self._formname(separator='_') options = self.options multiple = options.get('multiple', True) defaults = options.get('default', {}) if (fname in form.vars): try: data = json.loads(form.vars[fname]) except ValueError: return component_name = dat...
'Generate a string representing the formname @param separator: separator to prepend a prefix'
def _formname(self, separator=None):
if separator: return ('%s%s%s%s' % (self.prefix, separator, self.alias, self.selector)) else: return ('%s%s' % (self.alias, self.selector))
'Get the current layout'
def _layout(self):
layout = self.options.layout if (not layout): layout = current.deployment_settings.get_ui_inline_component_layout() elif isinstance(layout, type): layout = layout() return layout
'Render a read- or edit-row. @param table: the database table @param item: the data @param fields: the fields to render (list of strings) @param readonly: render a read-row (otherwise edit-row) @param editable: whether the record can be edited @param deletable: whether the record can be deleted @param multiple: whether...
def _render_item(self, table, item, fields, readonly=True, editable=False, deletable=False, multiple=True, index='none', layout=None, **attributes):
s3 = current.response.s3 rowtype = ((readonly and 'read') or 'edit') pkey = table._id.name data = {} formfields = [] formname = self._formname() widgets = self.widgets for f in fields: fname = f['name'] idxname = ('%s_i_%s_%s_%s' % (formname, fname, rowtype, index)) ...
'Render the filterby-options as Query to apply when retrieving the existing rows in this inline-component'
def _filterby_query(self):
filterby = self.options['filterby'] if (not filterby): return if (not isinstance(filterby, (list, tuple))): filterby = [filterby] component = self.resource.components[self.selector] table = component.table query = None for f in filterby: fieldname = f['field'] ...
'Render the defaults for this inline-component as a dict for the real-input JSON'
def _filterby_defaults(self):
if ('filterby' in self.options): filterby = self.options['filterby'] else: return None if (not isinstance(filterby, (list, tuple))): filterby = [filterby] component = self.resource.components[self.selector] table = component.table defaults = dict() for f in filterby: ...
'Re-render the options list for a field if there is a filterby-restriction. @param fieldname: the name of the field'
def _filterby_options(self, fieldname):
component = self.resource.components[self.selector] table = component.table if (fieldname not in table.fields): return None field = table[fieldname] filterby = self.options['filterby'] if (not isinstance(filterby, (list, tuple))): filterby = [filterby] filter_fields = dict(((...
'Find, rename and store an uploaded file and return it\'s new pathname'
def _store_file(self, table, fieldname, rowindex):
field = table[fieldname] formname = self._formname() upload = ('upload_%s_%s_%s' % (formname, fieldname, rowindex)) post_vars = current.request.post_vars if (upload in post_vars): f = post_vars[upload] if hasattr(f, 'file'): (sfile, ofilename) = (f.file, f.filename) ...
'Get all existing links for record_id. @param resource: the resource the record belongs to @param record_id: the record ID @return: list of component record IDs this record is linked to via the link table'
def extract(self, resource, record_id):
self.resource = resource (component, link) = self.get_link() from s3rest import S3Request r = S3Request(resource.prefix, resource.name, args=[], get_vars={}) customise_resource = current.deployment_settings.customise_resource for tablename in (component.tablename, link.tablename): custom...
'Widget renderer, currently supports multiselect (default), hierarchy and groupedopts widgets. @param field: the input field @param value: the value to populate the widget @param attributes: attributes for the widget @return: the widget'
def __call__(self, field, value, **attributes):
options = self.options (component, link) = self.get_link() has_permission = current.auth.s3_has_permission ltablename = link.tablename if ((options.readonly is True) or (not has_permission('create', ltablename)) or (not has_permission('delete', ltablename))): return self.represent(value) ...
'Validate this link, currently only checking whether it has a value when required=True @param form: the form'
def validate(self, form):
required = self.options.required if (not required): return fname = self._formname(separator='_') values = form.vars.get(fname) if (not values): error = (current.T('Value Required') if (required is True) else required) form.errors[fname] = error
'Post-processes this subform element against the POST data, and create/update/delete any related records. @param form: the master form @param master_id: the ID of the master record in the form @param format: the data format extension (for audit) @todo: implement audit'
def accept(self, form, master_id=None, format=None):
s3db = current.s3db fname = self._formname(separator='_') resource = self.resource success = False if (fname in form.vars): values = form.vars[fname] if (values is None): values = [] elif (not isinstance(values, (list, tuple, set))): values = [values] ...
'Read-only representation of this subform. @param value: the value as returned from extract() @return: the read-only representation'
def represent(self, value):
(component, link) = self.get_link() rkey = link.table[component.rkey] represent = rkey.represent if (not hasattr(represent, 'bulk')): lookup_field = None for fname in ('name', 'tag'): if (fname in component.fields): lookup_field = fname break ...
'Get the options for the widget @return: dict {value: representation} of options'
def get_options(self):
resource = self.resource (component, link) = self.get_link() rkey = link.table[component.rkey] opts = [] requires = rkey.requires if (not isinstance(requires, (list, tuple))): requires = [requires] if requires: validator = requires[0] if isinstance(validator, IS_EMPTY...
'Find the target component and its linktable @return: tuple of S3Resource instances (component, link)'
def get_link(self):
resource = self.resource selector = self.selector if (selector in resource.components): component = resource.components[selector] else: raise SyntaxError(('Undefined component: %s' % selector)) if (not component.link): raise SyntaxError(('No linktable for %s' %...
'Initialize this form element for a particular record. Retrieves the component data for this record from the database and converts them into a JSON string to populate the input field with. @param resource: the resource the record belongs to @param record_id: the record ID @return: the JSON for the input field.'
def extract(self, resource, record_id):
self.resource = resource component_name = self.selector if (component_name in resource.components): component = resource.components[component_name] if component.link: component = component.link table = component.table tablename = component.tablename pkey =...
'Widget method for this form element. Renders a table with checkboxes for all available options. This widget uses s3.inline_component.js to facilitate manipulation of the entries. @param field: the Field for this form element @param value: the current value for this field @param attributes: keyword attributes for this ...
def __call__(self, field, value, **attributes):
opts = self.options if (opts.readonly is True): return self.represent(value) if (value is None): value = field.default if isinstance(value, basestring): data = json.loads(value) else: data = value value = json.dumps(value, separators=SEPARATORS) if (data i...
'Build the Options'
def _options(self, data):
s3db = current.s3db opts = self.options resource = self.resource component_name = data['component'] component = resource.components[component_name] table = component.table option_help = opts.get('option_help', None) if option_help: fields = ['id', 'name', option_help] else: ...
'Read-only representation of this form element. This will be used instead of the __call__() method when the form element is to be rendered read-only. @param value: the value as returned from extract() @return: the read-only representation of this element as string or HTML helper'
def represent(self, value):
if isinstance(value, basestring): data = json.loads(value) else: data = value if (data['data'] == []): return current.messages['NONE'] fieldname = data['field'] items = data['data'] component = self.resource.components[data['component']] audit = current.audit (pre...
'Widget method for this form element. Renders a SELECT MULTIPLE with all available options. This widget uses s3.inline_component.js to facilitate manipulation of the entries. @param field: the Field for this form element @param value: the current value for this field @param attributes: keyword attributes for this widge...
def __call__(self, field, value, **attributes):
opts = self.options if (opts.readonly is True): return self.represent(value) if (value is None): value = field.default if isinstance(value, basestring): data = json.loads(value) else: data = value value = json.dumps(value, separators=SEPARATORS) if (data i...
'Represent the date according to deployment settings &/or T() @param dt: the date (datetime.date or datetime.datetime) @param format: the format (overrides deployment setting) @param utc: the date is given in UTC @param calendar: the calendar to use (defaults to current.calendar)'
@classmethod def date_represent(cls, dt, format=None, utc=False, calendar=None):
if (not format): format = current.deployment_settings.get_L10n_date_format() if (calendar is None): calendar = current.calendar elif isinstance(calendar, basestring): calendar = S3Calendar(calendar) if dt: if utc: offset = cls.get_offset_value(current.session....
'Represent the datetime according to deployment settings &/or T() @param dt: the datetime @param utc: the datetime is given in UTC @param calendar: the calendar to use (defaults to current.calendar)'
@classmethod def datetime_represent(cls, dt, format=None, utc=False, calendar=None):
if (format is None): format = current.deployment_settings.get_L10n_datetime_format() if (calendar is None): calendar = current.calendar elif isinstance(calendar, basestring): calendar = S3Calendar(calendar) if dt: if utc: offset = cls.get_offset_value(current....
'Represent the date according to deployment settings &/or T() @param time: the time @param format: the time format (overrides deployment setting) @param utc: the time is given in UTC'
@classmethod def time_represent(cls, time, format=None, utc=False):
settings = current.deployment_settings if (format is None): format = settings.get_L10n_time_format() if (time and utc): if (not isinstance(time, datetime.datetime)): today = datetime.datetime.utcnow().date() time = datetime.datetime.combine(today, time) offset...
'Convert an UTC offset string into a UTC offset value in seconds @param string: the UTC offset in hours as string, valid formats are: "+HH:MM", "+HHMM", "+HH" (positive sign can be omitted), can also recognize decimal notation with "." as mark'
@staticmethod def get_offset_value(string):
if (not string): return 0 sign = 1 offset_hrs = offset_min = 0 if isinstance(string, (int, long, float)): offset_hrs = string elif isinstance(string, basestring): if (string[:3] == 'UTC'): string = string[3:] string = string.strip() match = OFFSET....
'Convert a Julian day number to a year/month/day tuple of this calendar, to be implemented by subclass @param jd: the Julian day number'
@classmethod def from_jd(cls, jd):
return cls._jd_to_gregorian(jd)
'Convert a year/month/day tuple of this calendar into a Julian day number, to be implemented by subclass @param year: the year number @param month: the month number @param day: the day-of-month number'
@classmethod def to_jd(cls, year, month, day):
return cls._gregorian_to_jd(year, month, day)
'Get the name of the current'
@property def name(self):
name = self._name if (not name): name = current.deployment_settings.get_L10n_calendar() if (not name): name = self.CALENDAR return name
'Get the current calendar'
@property def calendar(self):
calendar = self._calendar if (calendar is None): calendar = self._set_calendar(self.name) return calendar
'Get the first day of the week for this calendar'
@property def first_dow(self):
calendar = self.calendar first_dow = calendar._first_dow if (first_dow is None): first_dow = current.deployment_settings.get_L10n_firstDOW() if (first_dow is None): first_dow = calendar.FIRST_DOW calendar._first_dow = first_dow return first_dow
'Parse a datetime string according to this calendar @param dtstr: the datetime as string @param dtfmt: the datetime format (strptime), overrides default @param local: whether the default format is local (=deployment setting) or ISO @return: the datetime (datetime.datetime)'
def parse_date(self, dtstr, dtfmt=None, local=False):
if (dtstr is None): return None if (dtfmt is None): if local: dtfmt = current.deployment_settings.get_L10n_date_format() else: dtfmt = '%Y-%m-%d' calendar = self.calendar try: timetuple = calendar._parse(dtstr, dtfmt) except (ValueError, TypeEr...
'Parse a datetime string according to this calendar @param dtstr: the datetime as string @param dtfmt: the datetime format (strptime) @param local: whether the default format is local (=deployment setting) or ISO @return: the datetime (datetime.datetime)'
def parse_datetime(self, dtstr, dtfmt=None, local=False):
if (dtstr is None): return None if (dtfmt is None): if local: dtfmt = current.deployment_settings.get_L10n_datetime_format() else: dtfmt = ISOFORMAT calendar = self.calendar try: timetuple = calendar._parse(dtstr, dtfmt) except (ValueError, Typ...
'Format a date according to this calendar @param dt: the date (datetime.date or datetime.datetime) @return: the date as string'
def format_date(self, dt, dtfmt=None, local=False):
if (dt is None): return current.messages['NONE'] if (dtfmt is None): if local: dtfmt = current.deployment_settings.get_L10n_date_format() else: dtfmt = '%Y-%m-%d' try: dtfmt = str(dtfmt) except (UnicodeDecodeError, UnicodeEncodeError): dtfm...
'Format a datetime according to this calendar @param dt: the datetime (datetime.datetime) @return: the datetime as string'
def format_datetime(self, dt, dtfmt=None, local=False):
if (dt is None): return current.messages['NONE'] if (dtfmt is None): if local: dtfmt = current.deployment_settings.get_L10n_datetime_format() else: dtfmt = ISOFORMAT try: dtfmt = str(dtfmt) except (UnicodeDecodeError, UnicodeEncodeError): d...