desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Reset the event matrix'
def _reset(self):
self._matrix = None self._rows = None self._cols = None self._reset_aggregates()
'Reset the aggregated values matrix'
def _reset_aggregates(self):
self.matrix = None self.rows = None self.cols = None self.totals = None
'Add a current event to this period @param event: the S3TimeSeriesEvent'
def add_current(self, event):
self.cevents[event.event_id] = event
'Add a previous event to this period @param event: the S3TimeSeriesEvent'
def add_previous(self, event):
self.pevents[event.event_id] = event
'Convert the aggregated results into a JSON-serializable dict @param rows: the row keys for the result @param cols: the column keys for the result @param isoformat: convert datetimes into ISO-formatted strings'
def as_dict(self, rows=None, cols=None, isoformat=True):
start = self.start if (start and isoformat): start = start.isoformat() end = self.end if (end and isoformat): end = end.isoformat() row_totals = None if (rows is not None): row_data = self.rows row_totals = [row_data.get(key) for key in rows] col_totals = None...
'Group events by their row and col axis values @param cumulative: include previous events'
def group(self, cumulative=False):
event_sets = [self.cevents] if cumulative: event_sets.append(self.pevents) rows = {} cols = {} matrix = {} from itertools import product for (index, events) in enumerate(event_sets): for (event_id, event) in events.items(): for key in event.rows: r...
'Group and aggregate the events in this period @param facts: list of facts to aggregate'
def aggregate(self, facts):
self._reset() rows = self.rows = {} cols = self.cols = {} matrix = self.matrix = {} totals = [] if (not isinstance(facts, (list, tuple))): facts = [facts] if any(((fact.method == 'cumulate') for fact in facts)): self.group(cumulative=True) else: self.group() f...
'Compute the total duration of the given event before the end of this period, in number of interval @param event: the S3TimeSeriesEvent @param interval: the interval expression (string)'
def duration(self, event, interval):
if ((event.end is None) or (event.end > self.end)): end_date = self.end else: end_date = event.end if ((event.start is None) or (event.start >= end_date)): result = 0 else: rule = self.get_rule(event.start, end_date, interval) if rule: result = rule.co...
'Convert a time slot string expression into a dateutil rrule within the context of a time period @param start: the start of the time period (datetime) @param end: the end of the time period (datetime) @param interval: time interval expression, like "days" or "2 weeks"'
@staticmethod def get_rule(start, end, interval):
match = re.match('\\s*(\\d*)\\s*([hdwmy]{1}).*', interval) if match: (num, delta) = match.groups() deltas = {'h': HOURLY, 'd': DAILY, 'w': WEEKLY, 'm': MONTHLY, 'y': YEARLY} if (delta not in deltas): return None else: num = (int(num) if num else 1) ...
'Constructor @param start: start of the time frame (datetime.datetime) @param end: end of the time frame (datetime.datetime) @param slot: length of time slots within the event frame, format: "{n }[hour|day|week|month|year]{s}", examples: "1 week", "3 months", "years"'
def __init__(self, start, end, slots=None):
if (start is None): raise SyntaxError('start time required') self.start = tp_tzsafe(start) if (end is None): end = datetime.datetime.utcnow() self.end = tp_tzsafe(end) self.empty = True self.baseline = None self.slots = slots self.periods = {} self.rule = self.g...
'Get the recurrence rule for the periods'
def get_rule(self):
slots = self.slots if (not slots): return None return S3TimeSeriesPeriod.get_rule(self.start, self.end, slots)
'Extend this time frame with events @param events: iterable of events @todo: integrate in constructor @todo: handle self.rule == None'
def extend(self, events):
if (not events): return empty = self.empty events = sorted(events) rule = self.rule periods = self.periods start = events[0].start if ((start is None) or (start <= self.start)): first = rule[0] else: first = rule.before(start, inc=True) current_events = {} ...
'Iterate over all periods within this event frame'
def __iter__(self):
periods = self.periods rule = self.rule if rule: for dt in rule: if (dt >= self.end): break if (dt in periods): (yield periods[dt]) else: end = rule.after(dt) if (not end): end = s...
'Constructor @param prefix: the table name prefix @param name: the table name @param c: the controller prefix @param f: the controller function @param args: list of request arguments @param vars: dict of request variables @param extension: the format extension (representation) @param get_vars: the URL query variables (...
def __init__(self, prefix=None, name=None, r=None, c=None, f=None, args=None, vars=None, extension=None, get_vars=None, post_vars=None, http=None):
auth = current.auth self.XSLT_PATH = 'static/formats' self.XSLT_EXTENSION = 'xsl' self.files = Storage() self.controller = (c or self.controller) self.function = (f or self.function) if ('.' in self.function): (self.function, ext) = self.function.split('.', 1) if (extension i...
'Set a method handler for this request @param method: the method name @param handler: the handler function @type handler: handler(S3Request, **attr) @param http: restrict to these HTTP methods, list|tuple @param representation: register handler for non-transformable data formats @param transform: register handler for t...
def set_handler(self, method, handler, http=None, representation=None, transform=False):
if (http is None): http = HTTP_METHODS elif (not isinstance(http, (tuple, list))): http = (http,) if transform: representation = ('__transform__',) elif (not representation): representation = (self.DEFAULT_REPRESENTATION,) elif (not isinstance(representation, (tuple, ...
'Get a method handler for this request @param method: the method name @param transform: get handler for transformable data format @return: the method handler'
def get_handler(self, method, transform=False):
handlers = self._handlers http_hooks = handlers.get(self.http) if (not http_hooks): return None DEFAULT_REPRESENTATION = self.DEFAULT_REPRESENTATION hooks = http_hooks.get(DEFAULT_REPRESENTATION) if hooks: method_hooks = dict(hooks) else: method_hooks = {} represe...
'Get the widget handler for a method @param r: the S3Request @param method: the widget method'
def get_widget_handler(self, method):
if self.component: resource = self.component if resource.link: resource = resource.link else: resource = self.resource (prefix, name) = (self.prefix, self.name) component_name = self.component_name custom_action = current.s3db.get_method(prefix, name, component_na...
'Parses the web2py request object'
def __parse(self):
self.id = None self.component_name = None self.component_id = None self.method = None tablename = ('%s_%s' % (self.prefix, self.name)) f = [] append = f.append args = self.args if (len(args) > 4): args = args[:4] method = self.name for arg in args: if ('.' in ...
'Process filters in POST, interprets URL filter expressions in POST vars (if multipart), or from JSON request body (if not multipart or $search=ajax). NB: overrides S3Request method as GET (r.http) to trigger the correct method handlers, but will not change current.request.env.request_method'
def __search(self):
get_vars = self.get_vars content_type = (self.env.get('content_type') or '') mode = get_vars.get('$search') if mode: self.http = 'GET' if (content_type == 'application/x-www-form-urlencoded'): filters = self.post_vars decode = None elif ((mode == 'ajax') or (content_type[...
'Execute this request @param attr: Parameters for the method handler'
def __call__(self, **attr):
response = current.response s3 = response.s3 self.next = None bypass = False output = None preprocess = None postprocess = None representation = self.representation if ((not self.id) and (representation == 'html')): if (self.component or (self.method in ('read', 'profile', 'u...
'Get the GET method handler'
def __GET(self, resource=None):
method = self.method transform = False if ((method is None) or (method in ('read', 'display', 'update'))): if self.transformable(): method = 'export_tree' transform = True elif self.component: resource = self.resource if (self.interactive and (...
'Get the PUT method handler'
def __PUT(self):
transform = self.transformable(method='import') method = self.method if ((not method) and transform): method = 'import_tree' return self.get_handler(method, transform=transform)
'Get the POST method handler'
def __POST(self):
if (self.method == 'delete'): return self.__DELETE() elif self.transformable(method='import'): return self.__PUT() else: post_vars = self.post_vars table = self.target()[2] if (('deleted' in table) and ('id' not in post_vars)): original = S3Resource.origin...
'Get the DELETE method handler'
def __DELETE(self):
if self.method: return self.get_handler(self.method) else: return self.get_handler('delete')
'XML Element tree export method @param r: the S3Request instance @param attr: controller attributes'
@staticmethod def get_tree(r, **attr):
get_vars = r.get_vars args = Storage() start = get_vars.get('start') if (start is not None): try: start = int(start) except ValueError: start = None limit = get_vars.get('limit') if (limit is not None): try: limit = int(limit) e...
'XML Element tree import method @param r: the S3Request method @param attr: controller attributes'
@staticmethod def put_tree(r, **attr):
get_vars = r.get_vars if ('ignore_errors' in get_vars): ignore_errors = True else: ignore_errors = False def findnames(get_vars, name): nlist = [] if (name in get_vars): names = get_vars[name] if isinstance(names, (list, tuple)): na...
'Resource structure introspection method @param r: the S3Request instance @param attr: controller attributes'
@staticmethod def get_struct(r, **attr):
response = current.response json_formats = response.s3.json_formats if (r.representation in json_formats): as_json = True content_type = 'application/json' else: as_json = False content_type = 'text/xml' get_vars = r.get_vars meta = (str(get_vars.get('meta', False...
'Resource structure introspection method (single table) @param r: the S3Request instance @param attr: controller attributes'
@staticmethod def get_fields(r, **attr):
representation = r.representation if (representation == 'xml'): output = r.resource.export_fields(component=r.component_name) content_type = 'text/xml' elif (representation == 's3json'): output = r.resource.export_fields(component=r.component_name, as_json=True) content_type ...
'Field options introspection method (single table) @param r: the S3Request instance @param attr: controller attributes'
@staticmethod def get_options(r, **attr):
get_vars = r.get_vars items = get_vars.get('field') if items: if (not isinstance(items, (list, tuple))): items = [items] fields = [] add_fields = fields.extend for item in items: f = item.split(',') if f: add_fields(f) e...
'Generate a new request for the same resource @param args: arguments for request constructor'
def factory(self, **args):
return s3_request(r=self, **args)
'Called upon S3Request.<key> - looks up the value for the <key> attribute. Falls back to current.request if the attribute is not defined in this S3Request. @param key: the key to lookup'
def __getattr__(self, key):
if (key in self.__dict__): return self.__dict__[key] sentinel = object() value = getattr(current.request, key, sentinel) if (value is sentinel): raise AttributeError return value
'Check the request for a transformable format @param method: "import" for import methods, else None'
def transformable(self, method=None):
if (self.representation in ('html', 'aadata', 'popup', 'iframe')): return False stylesheet = self.stylesheet(method=method, skip_error=True) if ((not stylesheet) and (self.representation != 'xml')): return False else: return True
'Determine whether to actuate a link or not @param component_id: the component_id (if not self.component_id)'
def actuate_link(self, component_id=None):
if (not component_id): component_id = self.component_id if self.component: single = (component_id != None) component = self.component if component.link: actuate = self.component.actuate if ('linked' in self.get_vars): linked = self.get_vars...
'Action upon unauthorised request'
@staticmethod def unauthorised():
current.auth.permission.fail()
'Action upon error @param status: HTTP status code @param message: the error message @param tree: the tree causing the error'
def error(self, status, message, tree=None, next=None):
if (self.representation == 'html'): current.session.error = message if (next is not None): redirect(next) else: redirect(URL(r=self, f='index')) else: headers = {'Content-Type': 'application/json'} current.log.error(message) raise HTTP(stat...
'Returns the URL of this request, use parameters to override current requests attributes: - None to keep current attribute (default) - 0 or "" to set attribute to NONE - value to use explicit value @param id: the master record ID @param component: the component name @param component_id: the component ID @param target: ...
def url(self, id=None, component=None, component_id=None, target=None, method=None, representation=None, vars=None, host=None):
if (vars is None): vars = self.get_vars elif (vars and isinstance(vars, str)): vars = json.loads(vars.replace("'", '"')) if ('format' in vars): del vars['format'] args = [] cname = self.component_name if (target is not None): if (cname and ((component is None) or ...
'Get the target table of the current request @return: a tuple of (prefix, name, table, tablename) of the target resource of this request @todo: update for link table support'
def target(self):
component = self.component if (component is not None): link = self.component.link if (link and (not self.actuate_link())): return (link.prefix, link.name, link.table, link.tablename) return (component.prefix, component.name, component.table, component.tablename) else: ...
'Find the XSLT stylesheet for this request @param method: "import" for data imports, else None @param skip_error: do not raise an HTTP error status if the stylesheet cannot be found'
def stylesheet(self, method=None, skip_error=False):
stylesheet = None format = self.representation if self.component: resourcename = self.component.name else: resourcename = self.name if (format == 'xml'): return stylesheet if ('transform' in self.vars): return self.vars['transform'] extension = self.XSLT_EXTEN...
'Read data from request body'
def read_body(self):
self.files = Storage() content_type = self.env.get('content_type') source = [] if (content_type and content_type.startswith('multipart/')): import cgi ext = ('.%s' % self.representation) post_vars = self.post_vars for v in post_vars: p = post_vars[v] ...
'Invoke the customization callback for a resource. @param tablename: the tablename of the resource; if called without tablename it will invoke the callbacks for the target resources of this request: - master - active component - active link table (in this order) Resource customization functions can be defined like: def...
def customise_resource(self, tablename=None):
if (tablename is None): customise = self.customise_resource customise(self.resource.tablename) component = self.component if component: customise(component.tablename) link = self.link if link: customise(link.tablename) else: db = cu...
'Entry point for the REST interface @param r: the S3Request @param method: the method established by the REST interface @param widget_id: widget ID @param attr: dict of parameters for the method handler @return: output object to send to the view'
def __call__(self, r, method=None, widget_id=None, **attr):
self.request = r response = current.response self.download_url = response.s3.download_url self.next = None if (method is not None): self.method = method else: self.method = r.method if r.component: component = r.component resource = component self.reco...
'Stub, to be implemented in subclass. This method is used to get the results as a standalone page. @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):
output = dict() return output
'Stub, to be implemented in subclass. This method is used by other method handlers to embed this method as widget. @note: For "html" format, the widget method must return an XML component that can be embedded in a DIV. If a dict is returned, it will be rendered against the view template of the calling method - the view...
def widget(self, r, method=None, widget_id=None, visible=True, **attr):
return None
'Check permission for the requested resource @param method: method to check, defaults to the actually requested method'
def _permitted(self, method=None):
auth = current.auth has_permission = auth.s3_has_permission r = self.request if (not method): method = self.method if (method in ('list', 'datatable', 'datalist')): method = 'read' if (r.component is None): table = r.table record_id = r.id else: table ...
'Get the ID of the target record of a S3Request @param r: the S3Request'
@staticmethod def _record_id(r):
master_id = r.id if r.component: component = r.component component_id = r.component_id link = r.link if ((not component.multiple) and (not component_id)): table = component.table pkey = table._id.name component.load(start=0, limit=1) ...
'Get a configuration setting of the current table @param key: the setting key @param default: the default value'
def _config(self, key, default=None):
return current.s3db.get_config(self.tablename, key, default)
'Get the path to the view template @param r: the S3Request @param default: name of the default view template'
@staticmethod def _view(r, default):
folder = r.folder prefix = r.controller exists = os.path.exists join = os.path.join settings = current.deployment_settings theme = settings.get_theme() location = settings.get_template_location() if (theme != 'default'): view = join(folder, location, 'templates', theme, 'views', ...
'Add additional view variables (invokes all callables) @param output: the output dict @param r: the S3Request @param attr: the view variables (e.g. \'rheader\') @note: overload this method in subclasses if you don\'t want additional view variables to be added automatically'
@staticmethod def _extend_view(output, r, **attr):
if (r.interactive and isinstance(output, dict)): for key in attr: handler = attr[key] if callable(handler): resolve = True try: display = handler(r) except TypeError: display = handler ...
'Remove all filters from URL vars @param vars: the URL vars as dict'
@staticmethod def _remove_filters(vars):
return Storage(((k, v) for (k, v) in vars.iteritems() if (not REGEX_FILTER.match(k))))
'Get a CRUD info string for interactive pages @param tablename: the table name @param name: the name of the CRUD string'
@staticmethod def crud_string(tablename, name):
crud_strings = current.response.s3.crud_strings _crud_strings = crud_strings.get(tablename, crud_strings) return _crud_strings.get(name, crud_strings.get(name))
'Page-render entry point for REST interface. @param r: the S3Request instance @param attr: controller attributes for the request'
def apply_method(self, r, **attr):
if (r.http == 'GET'): if (r.representation == 'geojson'): output = self.geojson(r, **attr) else: output = self.report(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) return output
'Pivot table report page @param r: the S3Request instance @param attr: controller attributes for the request'
def report(self, r, **attr):
output = {} resource = self.resource get_config = resource.get_config show_filter_form = False if (r.representation in ('html', 'iframe')): filter_widgets = get_config('filter_widgets', None) if (filter_widgets and (not self.hide_filter)): from s3filter import S3FilterFor...
'Render the pivot table data as a dict ready to be exported as GeoJSON for display on a Map. @param r: the S3Request instance @param attr: controller attributes for the request'
def geojson(self, r, **attr):
resource = self.resource response = current.response s3 = response.s3 response.headers['Content-Type'] = s3.content_type.get('geojson', 'application/json') if (not resource.count()): return json.dumps({}) get_vars = r.get_vars layer_id = r.get_vars.get('layer', None) level = get_...
'Pivot table report 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):
output = {} resource = self.resource get_config = resource.get_config maxrows = 20 maxcols = 20 report_vars = ('rows', 'cols', 'fact', 'totals') get_vars = dict(((k, v) for (k, v) in r.get_vars.iteritems() if (k in report_vars))) report_options = get_config('report_options', {}) defa...
'Render the form for the report @param get_vars: the GET vars if the request (as dict) @param widget_id: the HTML element base ID for the widgets'
def html(self, pivotdata, filter_widgets=None, get_vars=None, ajaxurl=None, filter_url=None, filter_form=None, filter_tab=None, widget_id=None):
T = current.T appname = current.request.application report_options = self.report_options(get_vars=get_vars, widget_id=widget_id) hidden = {'pivotdata': json.dumps(pivotdata, separators=SEPARATORS)} empty = T('No report specified.') hide = T('Hide Table') show = T('Show Table') ...
'Render the widgets for the report options form @param get_vars: the GET vars if the request (as dict) @param widget_id: the HTML element base ID for the widgets'
def report_options(self, get_vars=None, widget_id='pivottable'):
T = current.T SHOW_TOTALS = T('Show totals') REPORT = T('Report of') ROWS = T('Grouped by') COLS = T('and') resource = self.resource get_config = resource.get_config options = get_config('report_options') settings = current.deployment_settings formstyle = settings.get_ui...
'Construct an OptionsWidget for rows or cols axis @param axis: "rows" or "cols" @param options: the report options @param get_vars: the GET vars if the request (as dict) @param widget_id: the HTML element ID for the widget'
def axis_options(self, axis, options=None, get_vars=None, widget_id=None):
resource = self.resource prefix = resource.prefix_selector if (options and (axis in options)): fields = options[axis] else: fields = resource.get_config('list_fields') if (not fields): fields = [f.name for f in resource.readable_fields()] pkey = str(resource._id) reso...
'Construct an OptionsWidget for the fact layer @param options: the report options @param get_vars: the GET vars if the request (as dict) @param widget_id: the HTML element ID for the widget'
def layer_options(self, options=None, get_vars=None, widget_id=None):
resource = self.resource all_methods = S3PivotTableFact.METHODS layers = None methods = None if options: if ('methods' in options): methods = options['methods'] if ('fact' in options): layers = options['fact'] if (not layers): layers = resource.get...
'Helper method to wrap widgets in a FIELDSET container with show/hide option @param title: the title for the field set @param widgets: the widgets @param attr: HTML attributes for the field set'
@staticmethod def _fieldset(title, widgets, **attr):
T = current.T SHOW = T('Show') HIDE = T('Hide') return FIELDSET(LEGEND(title, BUTTON(SHOW, _type='button', _class='toggle-text'), BUTTON(HIDE, _type='button', _class='toggle-text')), widgets, **attr)
'Constructor @param method: the aggregation method @param selector: the field selector @param label: the fact label @param default_method: using default method (used by parser)'
def __init__(self, method, selector, label=None, default_method=True):
if (method is None): method = 'count' default_method = True if (method not in self.METHODS): raise SyntaxError(('Unsupported aggregation function: %s' % method)) self.method = method self.selector = selector self._layer = None self.label = label self.resource...
'Aggregate a list of values. @param values: iterable of values'
def compute(self, values, method=DEFAULT, totals=False):
if (values is None): return None if (method is DEFAULT): method = self.method if (totals and (method == 'list')): method = 'count' if ((method is None) or (method == 'list')): return (values if values else None) values = [v for v in values if (v != None)] if (meth...
'Aggregate totals for this fact (hyper-aggregation) @param totals: iterable of totals'
def aggregate_totals(self, totals):
if (self.method in ('list', 'count')): total = self.compute(totals, method='sum') else: total = self.compute(totals) return total
'Parse fact expression @param fact: the fact expression'
@classmethod def parse(cls, fact):
if isinstance(fact, tuple): (label, fact) = fact else: label = None if isinstance(fact, list): facts = [] for f in fact: facts.extend(cls.parse(f)) if (not facts): raise SyntaxError(('Invalid fact expression: %s' % fact)) retur...
'Get a label for a method @param code: the method code @return: the label (lazyT), or None for unsupported methods'
@classmethod def _get_method_label(cls, code):
methods = cls.METHODS if (code is None): code = 'list' if (code in methods): return current.T(methods[code]) else: return None
'Get the label for a field @param rfield: the S3ResourceField @param fact_options: the corresponding subset of the report options ("fact", "rows" or "cols")'
@staticmethod def _get_field_label(rfield, fact_options=None):
label = None if (not rfield): return resource = rfield.resource fields = (list(fact_options) if fact_options else []) list_fields = resource.get_config('list_fields') if list_fields: fields.extend(list_fields) prefix = resource.prefix_selector selector = prefix(rfield.sel...
'Get a label for this fact @param rfield: the S3ResourceField @param fact_options: the "fact" list of the report options'
def get_label(self, rfield, fact_options=None):
label = self.label if label: return label if fact_options: prefix = rfield.resource.prefix_selector for fact_option in fact_options: facts = self.parse(fact_option) for fact in facts: if ((fact.method == self.method) and (prefix(fact.selector) ...
'Constructor - extracts all unique records, generates a pivot table from them with the given dimensions and computes the aggregated values for each cell. @param resource: the S3Resource @param rows: field selector for the rows dimension @param cols: field selector for the columns dimension @param facts: list of S3Pivot...
def __init__(self, resource, rows, cols, facts, strict=True):
if ((not rows) and (not cols)): raise SyntaxError('No rows or columns specified for pivot table') self.resource = resource self.lfields = None self.dfields = None self.rfields = None self.rows = rows self.cols = cols self.facts = facts self.records = None...
'Total number of records in the report'
def __len__(self):
items = self.records if (items is None): return 0 else: return len(self.records)
'Render the pivot table data as a dict ready to be exported as GeoJSON for display on a Map. Called by S3Report.geojson() @param layer: the layer. e.g. ("id", "count") - we only support methods "count" & "sum" - @ToDo: Support density: \'per sqkm\' and \'per population\' @param level: the aggregation level (defaults to...
def geojson(self, fact=None, level='L0'):
if (fact is None): fact = self.facts[0] layer = fact.layer context = self.resource.get_config('context') if (context and ('location' in context)): rows_dim = ('(location)$%s' % level) else: rows_dim = ('location_id$%s' % level) attributes = {} geojsons = {} if sel...
'Render the pivot table data as JSON-serializable dict @param layer: the layer @param maxrows: maximum number of rows (None for all) @param maxcols: maximum number of columns (None for all) @param least: render the least n rows/columns rather than the top n (with maxrows/maxcols) labels: { layer: rows: cols: total: met...
def json(self, maxrows=None, maxcols=None):
rfields = self.rfields resource = self.resource T = current.T OTHER = '__other__' rows_dim = self.rows cols_dim = self.cols orows = [] rappend = orows.append ocols = [] cappend = ocols.append ocells = [] lookups = {} facts = self.facts if (not self.empty): ...
'Get the representation functions per fact field @param layers: the list of layers, tuples (selector, method)'
def _represents(self, layers):
rfields = self.rfields represents = {} values = self.values for (selector, method) in layers: if (selector in represents): continue rfield = rfields[selector] f = rfield.field if ((method in ('list', 'count')) and (f is not None) and hasattr(f.represent, 'bulk...
'Sort a dimension (sorts items in-place) @param items: the items as list of tuples (index, sort-total, totals, header) @param rfield: the dimension (S3ResourceField) @param index: alternative index of the value/text dict within each item'
@staticmethod def _sortdim(items, rfield, index=3):
if (not rfield): return ftype = rfield.ftype sortby = 'value' key = (lambda item: item[index][sortby]) if (ftype in ('integer', 'string')): requires = rfield.requires if isinstance(requires, (tuple, list)): requires = requires[0] if isinstance(requires, IS...
'Find the top/least <length> items (by total) @param items: the items as list of tuples (index, sort-total, totals, header) @param length: the maximum number of items @param least: find least rather than top @param facts: the facts to aggregate the tail totals'
@classmethod def _tail(cls, items, length=10, least=False, facts=None):
try: if (len(items) > length): l = list(items) l.sort((lambda x, y: int((y[1] - x[1])))) if least: l.reverse() keys = [item[0] for item in l[(length - 1):]] totals = [] for (i, fact) in enumerate(facts): ...
'Get the totals of a row/column/report @param values: the values dictionary @param facts: the facts @param append: callback to collect the totals for JSON data (currently only collects the first layer)'
@staticmethod def _totals(values, facts, append=None):
totals = [] number_represent = IS_NUMBER.represent for fact in facts: value = values[fact.layer] if ((not len(totals)) and (append is not None)): append(value) totals.append(s3_unicode(number_represent(value))) totals = ' / '.join(totals) return totals
'2-dimensional pivoting of a list of unique items @param items: list of unique items as dicts @param pkey_colname: column name of the primary key @param rows_colname: column name of the row dimension @param cols_colname: column name of the column dimension @return: tuple of (cell matrix, row headers, column headers), w...
@staticmethod def _pivot(items, pkey_colname, rows_colname, cols_colname):
rvalues = Storage() cvalues = Storage() cells = Storage() rindex = 0 cindex = 0 for item in items: rvalue = (item[rows_colname] if rows_colname else None) cvalue = (item[cols_colname] if cols_colname else None) if (rvalue not in rvalues): r = rvalues[rvalue] =...
'Compute an aggregation layer, updates: - self.cell: the aggregated values per cell - self.row: the totals per row - self.col: the totals per column - self.totals: the overall totals per layer @param matrix: the cell matrix @param fact: the fact field @param method: the aggregation method'
def _add_layer(self, matrix, fact):
rows = self.row cols = self.col records = self.records extract = self._extract resource = self.resource RECORDS = 'records' VALUES = 'values' table = resource.table pkey = table._id.name layer = fact.layer numcols = len(self.col) numrows = len(self.row) if (self.cell ...
'Determine the fields needed to generate the report @param fields: fields to include in the report (all fields)'
def _get_fields(self, fields=None):
resource = self.resource table = resource.table alias = resource.alias def prefix(s): if isinstance(s, (tuple, list)): return prefix(s[(-1)]) if ('.' not in s.split('$', 1)[0]): return ('%s.%s' % (alias, s)) elif (s[:2] == '~.'): return ('%s.%s...
'Get the representation method for a field in the report @param field: the field selector'
def _represent_method(self, field):
rfields = self.rfields default = (lambda value: None) if (field and (field in rfields)): rfield = rfields[field] if rfield.field: def repr_method(value): return s3_represent_value(rfield.field, value, strip_markup=True) elif rfield.virtual: rep...
'Extract a field value from a DAL row @param row: the row @param field: the fieldname (list_fields syntax)'
def _extract(self, row, field):
rfields = self.rfields if (field not in rfields): raise KeyError(('Invalid field name: %s' % field)) rfield = rfields[field] try: return rfield.extract(row) except AttributeError: return None
'Expand a data frame row into a list of rows for list:type values @param row: the row @param field: the field to expand (None for all fields) @param axisfilter: dict of filtered field values by column names'
def _expand(self, row, axisfilter=None):
pairs = [] append = pairs.append for colname in self.gfields.values(): if (not colname): continue value = row[colname] if (type(value) is list): if (not value): value = [None] if (axisfilter and (colname in axisfilter)): ...
'Apply CRUD methods @param r: the S3Request @param attr: controller parameters for the request @return: output object to send to the view'
def apply_method(self, r, **attr):
if (r.http == 'GET'): return self.form(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD)
'Generate an XForms form for the current resource @param r: the S3Request @param attr: controller parameters for the request'
def form(self, r, **attr):
resource = self.resource form = S3XFormsForm(resource.table) response = current.response response.headers['Content-Type'] = 'application/xhtml+xml' return form
'Retrieve a list of available XForms @return: a list of tuples (url, title) of available XForms'
@staticmethod def formlist():
resources = current.deployment_settings.get_xforms_resources() xforms = [] if resources: s3db = current.s3db for item in resources: options = {} if isinstance(item, (tuple, list)): if (len(item) == 2): (title, tablename) = item ...
'Constructor @param translate: enable/disable label translation'
def __init__(self, translate=True):
self.translate = translate self._strings = {}
'Form builder entry point @param field: the Field or a Storage with field information @param label: the label @param ref: the reference (string) that links the widget with the data model @return: tuple (widget, dict of i18n-strings)'
def __call__(self, field, label, ref):
if (not field): raise SyntaxError('Field is required') if (not ref): raise SyntaxError('Reference is required') self.ref = ref attr = {'_ref': ref} self.setstr('label', label) comment = field.comment if (comment and isinstance(comment, basestring)): self.s...
'Render the XForms Widget. @param field: the Field or a Storage with field information @param attr: dict with XML attributes for the widget, including the mandatory "ref" attribute that links the widget to the data model'
def widget(self, field, attr):
raise NotImplementedError
'Render the hint for this formfield @return: a <hint> element, or an empty tag if not available'
def hint(self):
return self.getstr('hint', 'hint', default=TAG['']())
'Render the label for this formfield @return: a <label> element, or an empty tag if not available'
def label(self):
return self.getstr('label', 'label')
'Add a translatable string to this widget @param key: the key for the string @param string: the string, or None to remove the key'
def setstr(self, key, string=None):
ref = ('%s:%s' % (self.ref, key)) strings = self._strings if string: if hasattr(string, 'flatten'): string = string.flatten() strings[ref] = string elif (key in strings): del strings[ref] return
'Get a translated string reference @param tag: the tag to wrap the string reference @param key: the key for the string'
def getstr(self, tag, key, default=None):
empty = False ref = ('%s:%s' % (self.ref, key)) translations = self._strings if (ref in translations): string = translations[ref] elif (default is not None): return default else: ref = None string = '' widget = TAG[str(tag)] if (self.translate and ref): ...
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
return TAG['input'](self.label(), self.hint(), **attr)
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
return TAG['input'](self.label(), self.hint(), **attr)
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
attr['_readonly'] = 'true' attr['_default'] = s3_unicode(field.default) return TAG['input'](self.label(), **attr)
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
requires = field.requires if (not hasattr(requires, 'options')): return TAG['input'](self.label(), **attr) items = ([self.label(), self.hint()] + self.items(requires.options())) return TAG['select1'](items, **attr)
'Render the items for the selector @param options: the options, list of tuples (value, text)'
def items(self, options):
items = [] setstr = self.setstr getstr = self.getstr for (index, option) in enumerate(options): (value, text) = option key = ('option%s' % index) if (hasattr(text, 'm') or hasattr(text, 'flatten')): setstr(key, text) text = getstr('label', key) els...
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
requires = field.requires if (not hasattr(requires, 'options')): return TAG['input'](self.label(), **attr) items = ([self.label(), self.hint()] + self.items(requires.options())) return TAG['select'](items, **attr)
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
T = current.T setstr = self.setstr setstr('false', T('No')) setstr('true', T('Yes')) getstr = self.getstr items = [self.label(), self.hint(), TAG['item'](getstr('label', 'true'), TAG['value'](1)), TAG['item'](getstr('label', 'true'), TAG['value'](0))] return TAG['select1'](items, **attr)
'Widget renderer (parameter description see base class)'
def widget(self, field, attr):
attr['_mediatype'] = 'image/*' return TAG['upload'](self.label(), self.hint(), **attr)
'Constructor @param tablename: the table name @param field: the Field or a Storage with field information @param translate: enable/disable label translation'
def __init__(self, tablename, field, translate=True):
self.tablename = tablename self.field = field self.name = field.name self.ref = ('/%s/%s' % (self.tablename, self.name)) self.translate = translate self._model = None self._binding = None self._strings = None self._widget = None
'The model node for this form field (lazy property)'
@property def model(self):
if (self._model is None): self._introspect() return self._model