desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor @param name: the name of the calendar (see _set_calendar for supported calendars). If constructed without name, the L10.calendar deployment setting will be used instead.'
def __init__(self, name=None):
self._calendars = {'Gregorian': S3Calendar, 'Persian': S3PersianCalendar, 'Afghan': S3AfghanCalendar, 'Nepali': S3NepaliCalendar} if (name is None): self._name = None self._calendar = None elif (name == self.CALENDAR): self._name = name self._calendar = self else: ...
'Set the current calendar @param name: the name of the calendar (falls back to CALENDAR)'
def _set_calendar(self, name=None):
calendars = self._calendars if (name not in calendars): name = self.CALENDAR if (name == self.CALENDAR): calendar = self else: calendar = calendars[name](name) self._name = name self._calendar = calendar return calendar
'Get a string representation for a datetime.datetime according to this calendar and dtfmt, to be implemented by subclass @param dt: the datetime.datetime @param dtfmt: the datetime format (strftime) @return: the string representation (str) @raises TypeError: for invalid argument types'
def _format(self, dt, dtfmt):
if (self.name == 'Gregorian'): fmt = str(dtfmt) try: dtstr = dt.strftime(fmt) except ValueError: year = ('%04i' % dt.year) fmt = fmt.replace('%Y', year).replace('%y', year[(-2):]) dtstr = dt.replace(year=1900).strftime(fmt) except Attri...
'Convert a time tuple from Gregorian calendar to this calendar @param timetuple: time tuple (y, m, d, hh, mm, ss) @return: time tuple (this calendar)'
def _cdate(self, timetuple):
if (self.name == 'Gregorian'): return timetuple (y, m, d, hh, mm, ss) = timetuple jd = self._gregorian_to_jd(y, m, d) (y, m, d) = self.from_jd(jd) return (y, m, d, hh, mm, ss)
'Convert a time tuple from this calendar to Gregorian calendar @param timetuple: time tuple (y, m, d, hh, mm, ss) @return: time tuple (Gregorian)'
def _gdate(self, timetuple):
if (self.name == 'Gregorian'): return timetuple (y, m, d, hh, mm, ss) = timetuple jd = self.to_jd(y, m, d) (y, m, d) = self._jd_to_gregorian(jd) return (y, m, d, hh, mm, ss)
'Convert a Gregorian date into a Julian day number (matching jQuery calendars algorithm) @param year: the year number @param month: the month number @param day: the day number'
@staticmethod def _gregorian_to_jd(year, month, day):
if (year < 0): year = (year + 1) if (month < 3): month = (month + 12) year = (year - 1) a = math.floor((year / 100)) b = ((2 - a) + math.floor((a / 4))) return ((((math.floor((365.25 * (year + 4716))) + math.floor((30.6001 * (month + 1)))) + day) + b) - 1524.5)
'Convert a Julian day number to a Gregorian date (matching jQuery calendars algorithm) @param jd: the Julian day number @return: tuple (year, month, day)'
@staticmethod def _jd_to_gregorian(jd):
z = math.floor((jd + 0.5)) a = math.floor(((z - 1867216.25) / 36524.25)) a = (((z + 1) + a) - math.floor((a / 4))) b = (a + 1524) c = math.floor(((b - 122.1) / 365.25)) d = math.floor((365.25 * c)) e = math.floor(((b - d) / 30.6001)) day = ((b - d) - math.floor((e * 30.6001))) if (e ...
'Convert a Julian day number to a year/month/day tuple of this calendar (matching jQuery calendars algorithm) @param jd: the Julian day number'
@classmethod def from_jd(cls, jd):
jd = (math.floor(jd) + 0.5) depoch = (jd - cls.to_jd(475, 1, 1)) cycle = math.floor((depoch / 1029983)) cyear = (depoch % 1029983) if (cyear != 1029982): aux1 = math.floor((cyear / 366)) aux2 = (cyear % 366) ycycle = ((math.floor(((((2134 * aux1) + (2816 * aux2)) + 2815) / 10...
'Convert a year/month/day tuple of this calendar into a Julian day number (matching jQuery calendars algorithm) @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):
if (year >= 0): ep_base = (year - 474) else: ep_base = (year - 473) ep_year = (474 + (ep_base % 2820)) if (month <= 7): mm = ((month - 1) * 31) else: mm = (((month - 1) * 30) + 6) result = ((((((day + mm) + math.floor((((ep_year * 682) - 110) / 2816))) + ((ep_year...
'Convert a Julian day number to a year/month/day tuple of this calendar (matching jQuery calendars algorithm) @param jd: the Julian day number'
@classmethod def from_jd(cls, jd):
(gyear, gmonth, gday) = cls._jd_to_gregorian(jd) gdoy = ((jd - cls._gregorian_to_jd(gyear, 1, 1)) + 1) year = (gyear + 56) cdata = cls._get_calendar_data(year) month = 9 rdays = ((cdata[month] - cdata[0]) + 1) while (gdoy > rdays): month += 1 if (month > 12): mont...
'Convert a year/month/day tuple of this calendar into a Julian day number (matching jQuery calendars algorithm) @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):
cmonth = month cyear = year if ((cmonth > 9) or ((cmonth == 9) and (day > cls._get_calendar_data(cyear)[0]))): gyear = (year - 56) else: gyear = (year - 57) gdoy = 0 if (month != 9): gdoy = day cmonth -= 1 cdata = cls._get_calendar_data(cyear) while (cmont...
'Helper method to determine the days in the individual months of the BS calendar, as well as the start of the year'
@classmethod def _get_calendar_data(cls, year):
default = [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30] return cls.NEPALI_CALENDAR_DATA.get(year, default)
'Constructor @param calendar: the calendar @param dtfmt: the date/time format'
def __init__(self, calendar, dtfmt=None):
if (not calendar): raise TypeError(('Invalid calendar: %s (%s)' % (calendar, type(calendar)))) self.calendar = calendar.calendar self.grammar = None self.rules = None self.set_format(dtfmt)
'Parse a date/time string @param string: the date/time string @return: a timetuple (y, m, d, hh, mm, ss)'
def parse(self, string):
if (not isinstance(string, basestring)): raise TypeError(('Invalid argument type: expected str, got %s' % type(string))) try: result = self.grammar.parseString(string) except self.ParseException: raise ValueError(('Invalid date/time: %s' % string)) return ...
'Update the date/time format for this parser, and generate the corresponding pyparsing grammar @param dtfmt: the date/time format'
def set_format(self, dtfmt):
if (not isinstance(dtfmt, basestring)): raise TypeError(('Invalid date/time format: %s (%s)' % (dtfmt, type(dtfmt)))) import pyparsing as pp self.ParseException = pp.ParseException from s3utils import s3_unicode rules = self.rules if (rules is None): rules = self.rule...
'Validate the parse result and convert it into a time tuple @param parse_result: the parse result @return: a timetuple (y, m, d, hh, mm, ss)'
def _validate(self, parse_result):
calendar = self.calendar now = current.request.utcnow today = (now.year, now.month, now.day, 0, 0, 0) (cyear, cmonth, cday) = calendar._cdate(today)[:3] year = parse_result.get('year4') if (year is None): year = parse_result.get('year2') if (year is None): year = cyea...
'Parser helper to convert a token into an integer number'
@staticmethod def _parse_int(s, l, tokens):
try: return int(tokens[0]) except (TypeError, ValueError): return None
'Generate the general pyparsing rules for this calendar @return: the rules dict rules = {"d": Day of the month as a zero-padded decimal number "b": Month as locale’s abbreviated name "B": Month as locale’s full name "m": Month as a zero-padded decimal number "y": Year without century as a zero-padded decimal number...
def _get_rules(self):
import pyparsing as pp T = current.T calendar = self.calendar oneOf = pp.oneOf parse_int = self._parse_int def numeric(minimum, maximum): ' Helper to define rules for zero-padded numeric values ' zp = ' '.join((('%02d' % i) for i in xrange(minimum, m...
'Constructor @param calendar: the calendar'
def __init__(self, calendar):
if (not calendar): raise TypeError(('Invalid calendar: %s (%s)' % (calendar, type(calendar)))) self.calendar = calendar.calendar
'Render a timetuple as string according to the given format @param timetuple: the timetuple (y, m, d, hh, mm, ss) @param dtfmt: the date/time format (string) @todo: support day-of-week options'
def render(self, timetuple, dtfmt):
(y, m, d, hh, mm, ss) = timetuple T = current.T calendar = self.calendar from s3utils import s3_unicode rules = {'d': ('%02d' % d), 'b': T(calendar.MONTH_ABBR[(m - 1)]), 'B': T(calendar.MONTH_NAME[(m - 1)]), 'm': ('%02d' % m), 'y': ('%02d' % (y % 100)), 'Y': ('%04d' % y), 'H': ('%02d' % hh), 'I': ('...
'Prototype method to render this widget as an instance of a web2py HTML helper class, to be implemented by subclasses. @param resource: the S3Resource to render with widget for @param values: the values for this widget from the URL query'
def widget(self, resource, values):
raise NotImplementedError
'Prototype method to generate the name for the URL query variable for this widget, can be overwritten in subclasses. @param resource: the resource @return: the URL query variable name (or list of variable names if there are multiple operators)'
def variable(self, resource, get_vars=None):
opts = self.opts if ('selector' in opts): (label, selector) = (None, opts['selector']) else: (label, selector) = self._selector(resource, self.field) self.selector = selector if (not selector): return None if (self.alternatives and (get_vars is not None)): operato...
'Prototype method to construct the hidden element that holds the URL query term corresponding to an input element in the widget. @param variable: the URL query variable'
def data_element(self, variable):
if (type(variable) is list): variable = '&'.join(variable) return INPUT(_type='hidden', _id=('%s-data' % self.attr['_id']), _class=('filter-widget-data %s-data' % self._class), _value=variable)
'Constructor to configure the widget @param field: the selector(s) for the field(s) to filter by @param attr: configuration options for this widget Common configuration options: @keyword label: label for the widget @keyword comment: comment for the widget @keyword hidden: render widget initially hidden (="advanced" opt...
def __init__(self, field=None, **attr):
self.field = field self.alias = None attributes = Storage() options = Storage() for (k, v) in attr.iteritems(): if (k[0] == '_'): attributes[k] = v else: options[k] = v self.attr = attributes self.opts = options self.selector = None self.values...
'Entry point for the form builder @param resource: the S3Resource to render the widget for @param get_vars: the GET vars (URL query vars) to prepopulate the widget @param alias: the resource alias to use'
def __call__(self, resource, get_vars=None, alias=None):
self.alias = alias self._attr(resource) variable = self.variable(resource, get_vars) defaults = {} for (k, v) in self.values.items(): selector = self._prefix(k) defaults[selector] = v if (type(variable) is list): values = Storage() for k in variable: i...
'Initialize and return the HTML attributes for this widget'
def _attr(self, resource):
_class = self._class attr = self.attr if ('_name' not in attr): if (not resource): raise SyntaxError(('%s: _name parameter required when rendered without resource.' % self.__class__.__name__)) flist = self.field if (not isinstance(flist, (list, tuple)...
'Helper method to get the operators from the URL query @param get_vars: the GET vars (a dict) @param selector: field selector @return: query operator - None, str or list'
@classmethod def _operator(cls, get_vars, selector):
variables = [('%s__%s' % (selector, op)) for op in cls.alternatives] slen = (len(selector) + 2) operators = [k[slen:] for (k, v) in get_vars.iteritems() if (k in variables)] if (not operators): return None elif (len(operators) == 1): return operators[0] else: return opera...
'Helper method to prefix an unprefixed field selector @param alias: the resource alias to use as prefix @param selector: the field selector @return: the prefixed selector'
def _prefix(self, selector):
alias = self.alias items = selector.split('$', 0) head = items[0] if ('.' in head): if (alias not in (None, '~')): (prefix, key) = head.split('.', 1) if (prefix == '~'): prefix = alias elif (prefix != alias): prefix = ('%s.%s' %...
'Helper method to generate a filter query selector for the given field(s) in the given resource. @param resource: the S3Resource @param fields: the field selectors (as strings) @return: the field label and the filter query selector, or None if none of the field selectors could be resolved'
def _selector(self, resource, fields):
prefix = self._prefix label = None if (not fields): return (label, None) if (not isinstance(fields, (list, tuple))): fields = [fields] selectors = [] for field in fields: if resource: try: rfield = S3ResourceField(resource, field) e...
'Helper method to get all values of a URL query variable @param get_vars: the GET vars (a dict) @param variable: the name of the query variable @return: a list of values'
@staticmethod def _values(get_vars, variable):
if (not variable): return [] elif (variable in get_vars): values = S3URLQuery.parse_value(get_vars[variable]) if (not isinstance(values, (list, tuple))): values = [values] return values else: return []
'Construct URL query variable(s) name from a filter query selector and the given operator(s) @param selector: the selector @param operator: the operator (or tuple/list of operators) @return: the URL query variable name (or list of variable names)'
@classmethod def _variable(cls, selector, operator):
if isinstance(operator, (tuple, list)): return [cls._variable(selector, o) for o in operator] elif operator: return ('%s__%s' % (selector, operator)) else: return selector
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self.attr if ('_size' not in attr): attr.update(_size='40') if (('_class' in attr) and attr['_class']): _class = ('%s %s' % (attr['_class'], self._class)) else: _class = self._class attr['_class'] = _class attr['_type'] = 'text' data = attr.get('data', {}) ...
'Overrides S3FilterWidget.data_element(), constructs multiple hidden INPUTs (one per variable) with element IDs of the form <id>-<operator>-data (where no operator is translated as "eq"). @param variables: the variables'
def data_element(self, variables):
if (variables is None): operators = self.operator if (type(operators) is not list): operators = [operators] variables = self._variable(self.selector, operators) else: if (type(variables) is not list): variables = [variables] operators = [(v.split('...
'Method to Ajax-retrieve the current options of this widget @param resource: the S3Resource'
def ajax_options(self, resource):
(min, max) = self._options(resource) attr = self._attr(resource) options = {attr['_id']: {'min': min, 'max': max}} return options
'Helper function to retrieve the current options for this filter widget @param resource: the S3Resource'
def _options(self, resource):
query = resource.get_query() rfilter = resource.rfilter if rfilter: join = rfilter.get_joins() left = rfilter.get_joins(left=True) else: join = left = None rfield = S3ResourceField(resource, self.field) field = rfield.field row = current.db(query).select(field.min(), ...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self.attr _class = self._class if (('_class' in attr) and attr['_class']): _class = ('%s %s' % (attr['_class'], _class)) else: _class = _class attr['_class'] = _class input_class = self._input_class input_labels = self.input_labels input_elements = DIV() ie_...
'Overrides S3FilterWidget.data_element(), constructs multiple hidden INPUTs (one per variable) with element IDs of the form <id>-<operator>-data (where no operator is translated as "eq"). @param variables: the variables'
def data_element(self, variables):
fields = self.field if (type(fields) is not list): return super(S3DateFilter, self).data_element(variables) selectors = self.selector.split('|') operators = self.operator elements = [] _id = self.attr['_id'] start = True for selector in selectors: if start: op...
'Method to Ajax-retrieve the current options of this widget @param resource: the S3Resource'
def ajax_options(self, resource):
auto_range = self.opts.get('auto_range') if (auto_range is None): auto_range = current.deployment_settings.get_search_dates_auto_range() if auto_range: (min, max, ts) = self._options(resource) attr = self._attr(resource) options = {attr['_id']: {'min': min, 'max': max, 'ts': ...
'Helper function to retrieve the current options for this filter widget @param resource: the S3Resource @param as_str: return date as ISO-formatted string not raw DateTime'
def _options(self, resource, as_str=True):
query = resource.get_query() rfilter = resource.rfilter if rfilter: join = rfilter.get_joins() left = rfilter.get_joins(left=True) else: join = left = None fields = self.field if (type(fields) is list): start_field = S3ResourceField(resource, fields[0]).field ...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self.attr _class = self._class if (('_class' in attr) and attr['_class']): _class = ('%s %s' % (attr['_class'], _class)) else: _class = _class _id = attr['_id'] T = current.T input_class = self._input_class input_labels = self.input_labels opts_get = self.op...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self.attr _class = self._class if (('_class' in attr) and attr['_class']): _class = ('%s %s' % (attr['_class'], _class)) else: _class = _class attr['_class'] = _class _id = attr['_id'] if resource: rfield = S3ResourceField(resource, self.field) field...
'Constructor to configure the widget @param field: the selector(s) for the field(s) to filter by @param attr: configuration options for this widget'
def __init__(self, field=None, **attr):
if (not field): field = 'location_id' settings = current.deployment_settings translate = settings.get_L10n_translate_gis_location() if translate: language = current.session.s3.language if (language == 'en'): translate = False self.translate = translate super(S...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self._attr(resource) opts = self.opts name = attr['_name'] (ftype, levels, noopt) = self._options(resource, values=values) if noopt: return SPAN(noopt, _class='no-options-available') _class = self._class if (('_class' in attr) and attr['_class']): _class = ('%s %s' ...
'Construct the hidden element that holds the URL query term corresponding to an input element in the widget. @param variable: the URL query variable'
def data_element(self, variable):
output = [] oappend = output.append i = 0 for level in self.levels: widget = INPUT(_type='hidden', _id=('%s-%s-data' % (self.attr['_id'], level)), _class=('filter-widget-data %s-data' % self._class), _value=variable[i]) oappend(widget) i += 1 return output
'Helper method to generate a filter query selector for the given field(s) in the given resource. @param resource: the S3Resource @param fields: the field selectors (as strings) @return: the field label and the filter query selector, or None if none of the field selectors could be resolved'
def _selector(self, resource, fields):
prefix = self._prefix if resource: rfield = S3ResourceField(resource, fields) label = rfield.label else: label = None if ('levels' in self.opts): levels = self.opts.levels else: levels = current.gis.get_relevant_hierarchy_levels() fields = [('%s$%s' % (fie...
'Construct URL query variable(s) name from a filter query selector and the given operator(s) @param selector: the selector @param operator: the operator (or tuple/list of operators) @return: the URL query variable name (or list of variable names)'
@classmethod def _variable(cls, selector, operator):
selectors = selector.split('|') return [('%s__%s' % (selector, operator)) for selector in selectors]
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
settings = current.deployment_settings if (not settings.get_gis_spatialdb()): current.log.warning('No Spatial DB => Cannot do Intersects Query yet => Disabling S3MapFilter') return '' attr_get = self.attr.get opts_get = self.opts.get _class = attr_get...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
attr = self._attr(resource) opts_get = self.opts.get name = attr['_name'] (ftype, options, noopt) = self._options(resource, values=values) if (options is None): options = [] hide_widget = True hide_noopt = '' else: options = OrderedDict(options) hide_widge...
'Method to Ajax-retrieve the current options of this widget @param resource: the S3Resource'
def ajax_options(self, resource):
opts = self.opts attr = self._attr(resource) (ftype, options, noopt) = self._options(resource) if (options is None): options = {attr['_id']: {'empty': str(noopt)}} else: cols = opts.get('cols', None) if cols: widget = S3GroupedOptionsWidget(options=options, multip...
'Helper function to retrieve the current options for this filter widget @param resource: the S3Resource'
def _options(self, resource, values=None):
T = current.T NOOPT = T('No options available') EMPTY = T('None') opts = self.opts selector = self.field if isinstance(selector, (tuple, list)): selector = selector[0] if (resource is None): rname = opts.get('resource') if rname: resource = current.s...
'Helper method to get all values of a URL query variable @param get_vars: the GET vars (a dict) @param variable: the name of the query variable @return: a list of values'
@staticmethod def _values(get_vars, variable):
if (not variable): return [] selector = variable.split('__', 1)[0] for key in (('%s__eq' % selector), selector, variable): if (key in get_vars): values = S3URLQuery.parse_value(get_vars[key]) if (not isinstance(values, (list, tuple))): values = [values...
'Render this widget as HTML helper object(s) @param resource: the resource @param values: the search values from the URL query'
def widget(self, resource, values):
selected = [] append = selected.append if (not isinstance(values, (list, tuple, set))): values = [values] for v in values: if (isinstance(v, (int, long)) or str(v).isdigit()): append(v) rfield = S3ResourceField(resource, self.field) opts = self.opts bulk_select = ...
'Generate the name for the URL query variable for this widget, detect alternative __typeof queries. @param resource: the resource @return: the URL query variable name (or list of variable names if there are multiple operators)'
def variable(self, resource, get_vars=None):
(label, self.selector) = self._selector(resource, self.field) if (not self.selector): return None if ('label' not in self.opts): self.opts['label'] = label selector = self.selector if (self.alternatives and (get_vars is not None)): operator = self._operator(get_vars, self.sel...
'Constructor @param widgets: the widgets (as list) @param attr: HTML attributes for this form'
def __init__(self, widgets, **attr):
self.widgets = widgets attributes = Storage() options = Storage() for (k, v) in attr.iteritems(): if (k[0] == '_'): attributes[k] = v else: options[k] = v self.attr = attributes self.opts = options
'Render this filter form as HTML form. @param resource: the S3Resource @param get_vars: the request GET vars (URL query dict) @param target: the HTML element ID of the target object for this filter form (e.g. a datatable) @param alias: the resource alias to use in widgets'
def html(self, resource, get_vars=None, target=None, alias=None):
attr = self.attr form_id = attr.get('_id') if (not form_id): form_id = 'filter-form' attr['_id'] = form_id attr['_autocomplete'] = 'off' opts_get = self.opts.get settings = current.deployment_settings formstyle = opts_get('formstyle', None) if (not formstyle): formsty...
'Render the filter widgets without FORM wrapper, e.g. to embed them as fieldset in another form. @param resource: the S3Resource @param get_vars: the request GET vars (URL query dict) @param alias: the resource alias to use in widgets'
def fields(self, resource, get_vars=None, alias=None):
formstyle = self.opts.get('formstyle', None) if (not formstyle): formstyle = current.deployment_settings.get_ui_filter_formstyle() rows = self._render_widgets(resource, get_vars=get_vars, alias=alias, formstyle=formstyle) controls = self._render_controls(resource) if controls: rows.a...
'Render optional additional filter form controls: advanced options toggle, clear filters.'
def _render_controls(self, resource):
T = current.T controls = [] opts = self.opts advanced = opts.get('advanced', False) if advanced: _class = 'filter-advanced' if (advanced is True): label = T('More Options') elif isinstance(advanced, (list, tuple)): label = advanced[0] la...
'Render the filter widgets @param resource: the S3Resource @param get_vars: the request GET vars (URL query dict) @param alias: the resource alias to use in widgets @param formstyle: the formstyle to use @return: a list of form rows'
def _render_widgets(self, resource, get_vars=None, alias=None, formstyle=None):
rows = [] rappend = rows.append advanced = False for f in self.widgets: widget = f(resource, get_vars, alias=alias) widget_opts = f.opts label = widget_opts['label'] comment = widget_opts['comment'] hidden = widget_opts['hidden'] widget_formstyle = widget_...
'Render a filter manager widget @param resource: the resource @return: the widget'
def _render_filters(self, resource, form_id):
SELECT_FILTER = current.T('Saved Filters') ajaxurl = self.opts.get('saveurl', URL(args=['filter.json'], vars={})) auth = current.auth pe_id = (auth.user.pe_id if auth.s3_logged_in() else None) if (not pe_id): return None table = current.s3db.pr_filter query = ((table.deleted != Tr...
'Render this filter form as JSON (for Ajax requests) @param resource: the S3Resource @param get_vars: the request GET vars (URL query dict)'
def json(self, resource, get_vars=None):
raise NotImplementedError
'Add default filters to resource, to be called a multi-record view with a filter form is rendered the first time and before the view elements get processed @param request: the request @param resource: the resource @return: dict with default filters (URL vars)'
@staticmethod def apply_filter_defaults(request, resource):
s3 = current.response.s3 get_vars = request.get_vars tablename = resource.tablename default_filters = {} filter_defaults = s3 for level in ('filter_defaults', tablename): if (level not in filter_defaults): filter_defaults = None break filter_defaults = fil...
'Entry point for REST interface @param r: the S3Request @param attr: additional controller parameters'
def apply_method(self, r, **attr):
representation = r.representation if (representation == 'options'): return self._options(r, **attr) elif (representation == 'json'): if (r.http == 'GET'): return self._load(r, **attr) elif (r.http == 'POST'): if ('delete' in r.get_vars): return...
'Get the filter form for the target resource as HTML snippet GET filter.html @param r: the S3Request @param attr: additional controller parameters'
def _form(self, r, **attr):
r.error(501, current.ERROR.NOT_IMPLEMENTED)
'Get the updated options for the filter form for the target resource as JSON. NB These use a fresh resource, so filter vars are not respected. s3.filter if respected, so if you need to filter the options, then can apply filter vars to s3.filter in customise() if the controller is not the same as the calling one! GET fi...
def _options(self, r, **attr):
resource = self.resource options = {} filter_widgets = resource.get_config('filter_widgets', None) if filter_widgets: fresource = current.s3db.resource(resource.tablename, filter=current.response.s3.filter) for widget in filter_widgets: if hasattr(widget, 'ajax_options'): ...
'Delete a filter, responds to POST filter.json?delete= @param r: the S3Request @param attr: additional controller parameters'
def _delete(self, r, **attr):
auth = current.auth if auth.s3_logged_in(): pe_id = current.auth.user.pe_id else: pe_id = None if (not pe_id): r.unauthorised() source = r.body source.seek(0) try: data = json.load(source) except ValueError: r.error(501, current.ERROR.BAD_SOURCE) ...
'Save a filter, responds to POST filter.json @param r: the S3Request @param attr: additional controller parameters'
def _save(self, r, **attr):
auth = current.auth if auth.s3_logged_in(): pe_id = current.auth.user.pe_id else: pe_id = None if (not pe_id): r.unauthorised() source = r.body source.seek(0) try: data = json.load(source) except ValueError: r.error(501, current.ERROR.BAD_SOURCE) ...
'Load filters GET filter.json or GET filter.json?load=<id> @param r: the S3Request @param attr: additional controller parameters'
def _load(self, r, **attr):
db = current.db table = current.s3db.pr_filter auth = current.auth if auth.s3_logged_in(): pe_id = current.auth.user.pe_id else: pe_id = None if (not pe_id): r.unauthorized() query = (((table.deleted != True) & (table.resource == self.resource.tablename)) & (table.pe_...
'Constructor @param query: the URL query (list of key-value pairs or a string with such a list in JSON)'
def __init__(self, resource, query):
if (type(query) is not list): try: self.query = json.loads(query) except ValueError: self.query = [] else: self.query = query get_vars = {} for (k, v) in self.query: if (v is not None): key = resource.prefix_selector(k) if (...
'Render the query representation for the given resource'
def represent(self):
default = '' get_vars = self.get_vars resource = self.resource if (not get_vars): return default else: queries = S3URLQuery.parse(resource, get_vars) labels = {} get_config = resource.get_config prefix = resource.prefix_selector for config in ('list_fields', 'notify_f...
'Recursively render a human-readable representation of a S3ResourceQuery. @param resource: the S3Resource @param query: the S3ResourceQuery @param invert: invert the query'
@classmethod def _render(cls, resource, alias, query, invert=False, labels=None):
T = current.T if (not query): return None op = query.op l = query.left r = query.right render = (lambda q, r=resource, a=alias, invert=False, labels=labels: cls._render(r, a, q, invert=invert, labels=labels)) if (op == query.AND): l = render(l) r = render(r) i...
'Convert a filter value according to the field type before representation @param rfield: the S3ResourceField @param value: the value'
@classmethod def _convert(cls, rfield, value):
if (value is None): return value ftype = rfield.ftype if (ftype[:5] == 'list:'): if (ftype[5:8] in ('int', 'ref')): ftype = long else: ftype = unicode elif ((ftype == 'id') or (ftype[:9] == 'reference')): ftype = long elif (ftype == 'integer'):...
'Translate the filter query into human-readable language @param query: the S3ResourceQuery @param rfield: the S3ResourceField the query refers to @param values: the filter values @param invert: invert the operation'
@classmethod def _translate_query(cls, query, rfield, values, invert=False):
T = current.T vor = T('%s or %s') vand = T('%s and %s') otemplates = {query.LT: (query.GE, vand, '%(label)s < %(values)s'), query.LE: (query.GT, vand, '%(label)s <= %(values)s'), query.EQ: (query.NE, vor, T('%(label)s is %(values)s')), query.GE: (query.LT, vand, '%(label)s ...
'Apply CRUD methods @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view'
def apply_method(self, r, **attr):
self.settings = current.response.s3.crud sqlform = self._config('crud_form') self.sqlform = (sqlform if sqlform else S3SQLDefaultForm()) self.data = None if ((r.http == 'GET') and (not self.record_id)): populate = attr.pop('populate', None) if callable(populate): try: ...
'Entry point for other method handlers to embed this method as widget @param r: the S3Request @param method: the widget method @param widget_id: the widget ID @param visible: whether the widget is initially visible @param attr: controller attributes'
def widget(self, r, method=None, widget_id=None, visible=True, **attr):
self.settings = current.response.s3.crud sqlform = self._config('crud_form') self.sqlform = (sqlform if sqlform else S3SQLDefaultForm()) _attr = Storage(attr) _attr['list_id'] = widget_id if (method == 'datatable'): output = self._datatable(r, **_attr) if isinstance(output, dict)...
'Create new records @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def create(self, r, **attr):
session = current.session request = self.request response = current.response resource = self.resource table = resource.table tablename = resource.tablename representation = r.representation output = dict() native = (r.method == 'create') _config = self._config insertable = _c...
'Create-buttons/form in summary views, both GET and POST @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def _widget_create(self, r, **attr):
response = current.response resource = self.resource get_config = resource.get_config tablename = resource.tablename output = {} insertable = get_config('insertable', True) if insertable: listadd = get_config('listadd', True) addbtn = get_config('addbtn', False) if li...
'Read a single record @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def read(self, r, **attr):
authorised = self._permitted() if (not authorised): r.unauthorised() request = self.request response = current.response resource = self.resource table = resource.table tablename = resource.tablename representation = r.representation output = dict() _config = self._config ...
'Update a record @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def update(self, r, **attr):
resource = self.resource table = resource.table tablename = resource.tablename representation = r.representation output = dict() _config = self._config editable = _config('editable', True) onvalidation = (_config('update_onvalidation') or _config('onvalidation')) onaccept = (_config(...
'Delete record(s) @param r: the S3Request @param attr: dictionary of parameters for the method handler @todo: update for link table components'
def delete(self, r, **attr):
output = dict() config = self._config deletable = config('deletable', True) delete_next = config('delete_next', None) if (not deletable): r.error(403, current.ERROR.NOT_PERMITTED, next=r.url(method='')) record_id = self.record_id authorised = self._permitted() if (not authorised)...
'Filterable datatable/datalist @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def select(self, r, **attr):
resource = self.resource tablename = resource.tablename get_config = resource.get_config list_fields = get_config('list_fields', None) representation = r.representation if (representation in ('html', 'iframe', 'aadata', 'dl', 'popup')): hide_filter = self.hide_filter filter_widge...
'Get a data table @param r: the S3Request @param attr: parameters for the method handler'
def _datatable(self, r, **attr):
authorised = self._permitted() if (not authorised): r.unauthorised() resource = self.resource get_config = resource.get_config linkto = get_config('linkto', None) list_id = attr.get('list_id', 'datatable') list_fields = resource.list_fields() orderby = get_config('orderby', None)...
'Get a data list @param r: the S3Request @param attr: parameters for the method handler'
def _datalist(self, r, **attr):
authorised = self._permitted() if (not authorised): r.unauthorised() resource = self.resource get_config = resource.get_config get_vars = self.request.get_vars layout = get_config('list_layout', None) list_id = get_vars.get('list_id', attr.get('list_id', 'datalist')) if hasattr(l...
'Get a list of unapproved records in this resource @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def unapproved(self, r, **attr):
session = current.session response = current.response s3 = response.s3 resource = self.resource table = self.table representation = r.representation output = dict() _config = self._config orderby = _config('orderby', None) linkto = _config('linkto', None) list_fields = _confi...
'Review/approve/reject an unapproved record. @param r: the S3Request @param attr: dictionary of parameters for the method handler'
def review(self, r, **attr):
if (not self._permitted('review')): r.unauthorized() T = current.T session = current.session response = current.response output = Storage() if r.interactive: _next = r.url(id='[id]', method='review') if self._permitted('approve'): approve = FORM(INPUT(_value=T...
'Validate records (AJAX). This method reads a JSON object from the request body, validates it against the current resource, and returns a JSON object with either the validation errors or the text representations of the data. @param r: the S3Request @param attr: dictionary of parameters for the method handler Input JSON...
def validate(self, r, **attr):
if (r.representation != 'json'): r.error(415, current.ERROR.BAD_FORMAT) resource = self.resource get_vars = r.get_vars if ('component' in get_vars): alias = get_vars['component'] else: alias = None if ('resource' in get_vars): tablename = get_vars['resource'] ...
'Generate a CRUD action button @param label: the link label (None if using CRUD string) @param tablename: the name of table for CRUD string selection @param name: name of CRUD string for the button label @param icon: name of the icon (e.g. "add") @param _href: the target URL @param _id: the HTML id of the link @param _...
@staticmethod def crud_button(label=None, tablename=None, name=None, icon=None, _href=None, _id=None, _class=None, _title=None, _target=None, **attr):
settings = current.deployment_settings bootstrap = (settings.ui.formstyle == 'bootstrap') if ('custom' in attr): custom = attr['custom'] if (custom is None): custom = '' elif (bootstrap and hasattr(custom, 'add_class')): custom.add_class('btn btn-primary') ...
'Get the last update meta-data of the current record @return: a dict {modified_by: <user>, modified_on: <datestr>}, depending on which of these attributes are available in the current record'
def last_update(self):
output = {} record_id = self.record_id if record_id: record = None fields = [] table = self.table if ('modified_on' in table.fields): fields.append(table.modified_on) if ('modified_by' in table.fields): fields.append(table.modified_by) ...
'Render CRUD buttons @param r: the S3Request @param buttons: list of button names, any of: "add", "edit", "delete", "list", "summary" @param record_id: the record ID @param attr: the controller attributes @return: a dict of buttons for the view'
def render_buttons(self, r, buttons, record_id=None, **attr):
output = {} custom_crud_buttons = attr.get('custom_crud_buttons', {}) tablename = self.tablename representation = r.representation url = r.url remove_filters = self._remove_filters crud_string = self.crud_string config = self._config crud_button = self.crud_button if (('add' in b...
'Add a link to response.s3.actions @param label: the link label @param url: the target URL @param attr: attributes for the link (default: {"_class":"action-btn"})'
@staticmethod def action_button(label, url, icon=None, **attr):
link = dict(attr) link['label'] = s3_str(label) link['url'] = url if (icon and current.deployment_settings.get_ui_use_button_icons()): link['icon'] = ICON.css_class(icon) if ('_class' not in link): link['_class'] = 'action-btn' s3 = current.response.s3 if (s3.actions is None)...
'Provide the usual action buttons in list views. Allow customizing the urls, since this overwrites anything that would be inserted by CRUD/select via linkto. The resource id should be represented by "[id]". @param r: the S3Request @param deletable: records can be deleted @param editable: records can be modified @param ...
@classmethod def action_buttons(cls, r, deletable=True, editable=True, copyable=False, read_url=None, delete_url=None, update_url=None, copy_url=None):
s3crud = S3CRUD s3 = current.response.s3 labels = s3.crud_labels custom_actions = s3.actions s3.actions = None auth = current.auth has_permission = auth.s3_has_permission ownership_required = auth.permission.ownership_required if r.component: table = r.component.table ...
'Show a default cancel button in standalone create/update forms. Individual controllers can override this by setting response.s3.cancel = False. @param r: the S3Request'
def _default_cancel_button(self, r):
if (r.representation != 'html'): return False s3 = current.response.s3 cancel = s3.cancel if ((cancel is False) or isinstance(cancel, dict)): success = False elif ((cancel is True) or current.deployment_settings.get_ui_default_cancel_button()): if isinstance(cancel, basestrin...
'Import CSV file into database @param file: file handle @param table: the table to import to'
def import_csv(self, file, table=None):
if table: table.import_from_csv_file(file) else: db = current.db db.import_from_csv_file(file) db.commit()
'Import data from vars in URL query @param r: the S3Request @note: can only update single records (no mass-update) @todo: update for link table components @todo: re-integrate into S3Importer'
@staticmethod def import_url(r):
xml = current.xml (prefix, name, table, tablename) = r.target() record = r.record resource = r.resource if (record and r.component): resource = resource.components[r.component_name] resource.load() if (len(resource) == 1): record = resource.records()[0] el...
'Renders the right key constraint in a link table as S3EmbeddedComponentWidget and stores the postprocess hook. @param resource: the link table resource'
def _embed_component(self, resource, record=None):
link = None component = resource.linked if ((component is not None) and (component.actuate == 'embed')): ctablename = component.tablename attr = {'link': resource.tablename, 'component': ctablename} autocomplete = component.autocomplete if (autocomplete and (autocomplete in c...
'Post-processes a form with an S3EmbeddedComponentWidget and created/updates the component record. @param form: the form @param component: the component tablename @param key: the field name of the foreign key for the component in the link table'
def _postprocess_embedded(self, form, component=None, key=None):
s3db = current.s3db request = current.request get_config = (lambda key, tablename=component: s3db.get_config(tablename, key, None)) try: selected = form.vars[key] except: selected = None if (request.env.request_method == 'POST'): db = current.db table = db[compone...
'Returns a linker function for the record ID column in list views @param r: the S3Request @param authorised: user authorised for update (override internal check) @param update: provide link to update rather than to read @param native: link to the native controller rather than to component controller'
def _linkto(self, r, authorised=None, update=None, native=False):
c = None f = None s3db = current.s3db (prefix, name, table, tablename) = r.target() permit = current.auth.s3_has_permission if (authorised is None): authorised = permit('update', tablename) if (authorised and update): linkto = s3db.get_config(tablename, 'linkto_update', None)...
'Retain certain GET vars of the request in action links @param r: the S3Request @return: Storage with GET vars'
@staticmethod def _linkto_vars(r):
get_vars = r.get_vars linkto_vars = Storage() if ((not r.component) and ('viewing' in get_vars)): linkto_vars.viewing = get_vars['viewing'] keep_vars = current.response.s3.crud.keep_vars if keep_vars: for key in keep_vars: if (key in get_vars): linkto_vars...
'Render an additional custom submit button for interim save, which overrides the default _next to returns to an update form for the same record after create/update'
@staticmethod def _interim_save_button():
label = current.deployment_settings.get_ui_interim_save() if label: _class = 'interim-save' if isinstance(label, basestring): label = current.T(label) elif (isinstance(label, (tuple, list)) and (len(label) > 1)): (label, _class) = label[:2] elif (not isins...
'Extract page limits (start and limit) from GET vars @param get_vars: the GET vars @param default_limit: the default limit, explicit value or: 0 => response.s3.ROWSPERPAGE None => no default limit'
@staticmethod def _limits(get_vars, default_limit=0):
start = get_vars.get('start', None) limit = get_vars.get('limit', default_limit) if isinstance(start, list): start = start[(-1)] if isinstance(limit, list): limit = limit[(-1)] if limit: if (isinstance(limit, basestring) and (limit.lower() == 'none')): limit = Non...
'Constructor'
def __init__(self):
T = current.T s3db = current.s3db settings = current.deployment_settings formlist = [] formdict = {} forms = settings.get_mobile_forms() if forms: keys = set() for item in forms: options = {} if isinstance(item, (tuple, list)): if (len(...