desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The binding for this form field (lazy property)'
@property def binding(self):
if (self._binding is None): self._introspect() return self._binding
'The dict of i18n-strings for this form field (lazy property)'
@property def strings(self):
if (self._strings is None): self._introspect() return self._strings
'The widget for this form field (lazy property)'
@property def widget(self):
if (self._widget is None): self._introspect() return self._widget
'Introspect the field type and constraints, generate model, binding and widget and extract i18n strings. The results can be accessed via the lazy properties model, binding, widget, and strings. @return: nothing'
def _introspect(self):
field = self.field self._strings = {} self._model = TAG[self.name]() readonly = None required = None if (not field.writable): readonly = 'true()' elif self._required(field): required = 'true()' attr = {'_nodeset': self.ref, '_required': required, '_readonly': readonly} ...
'Introspect range constraints, convert to string for binding @param validators: a sequence of validators @return: a string with the range constraints'
@staticmethod def _range(validators):
constraints = [] for validator in validators: if hasattr(validator, 'other'): v = validator.other else: v = validator if isinstance(v, (IS_INT_IN_RANGE, IS_FLOAT_IN_RANGE)): maximum = v.maximum if (maximum is not None): cons...
'Determine whether field is required @param field: the Field or a Storage with field information @return: True if field is required, else False'
@staticmethod def _required(field):
required = False validators = field.requires if isinstance(validators, IS_EMPTY_OR): required = False else: required = (field.required or field.notnull) if ((not required) and validators): if (not isinstance(validators, (list, tuple))): validators = [validators] ...
'Constructor @param table: the database table @param name: optional alternative form name @param translate: enable/disable translation of strings'
def __init__(self, table, name=None, translate=True):
self.table = table if name: self.name = name elif hasattr(table, '_tablename'): self.name = table._tablename else: self.name = str(table) fields = [] append = fields.append for field in table: if field.readable: append(S3XFormsField(table, field, t...
'Render this form as XML string @return: XML as string'
def xml(self):
ns = {'_xmlns': 'http://www.w3.org/2002/xforms', '_xmlns:h': 'http://www.w3.org/1999/xhtml', '_xmlns:ev': 'http://www.w3.org/2001/xml-events', '_xmlns:xsd': 'http://www.w3.org/2001/XMLSchema', '_xmlns:jr': 'http://openrosa.org/javarosa'} document = TAG['h:html'](self._head(), self._body(), **ns) return docu...
'Get the HTML head for this form @return: an <h:head> tag'
def _head(self):
title = TAG['h:title'](self.name) model = self._model() return TAG['h:head'](title, model)
'Get the HTML body for this form @return: an <h:body> tag'
def _body(self):
widgets = self._widgets() return TAG['h:body'](widgets)
'Get the model for this form @return: a <model> tag with instance, bindings and i18n strings'
def _model(self):
instance = self._instance() bindings = self._bindings() translations = self._translations() return TAG['model'](instance, bindings, translations)
'Get the instance for this form @return: an <instance> tag with all form field nodes'
def _instance(self):
nodes = [] append = nodes.append for field in self._fields: append(field.model) return TAG['instance'](TAG[self.name](nodes), _id=self.name)
'Get the bindings for this form @return: a TAG with the bindings'
def _bindings(self):
bindings = [] append = bindings.append for field in self._fields: append(field.binding) return TAG[''](bindings)
'Get the widgets for this form @return: a TAG with the widgets'
def _widgets(self):
strings = self._strings widgets = [] append = widgets.append fields = self._fields for field in self._fields: append(field.widget) return TAG[''](widgets)
'Get a dict with all i18n strings for this form @return: a dict {key: string}'
def _strings(self):
strings = {} if self.translate: update = strings.update for field in self._fields: update(field.strings) return strings
'Render the translations for all configured languages @returns: translation tags'
def _translations(self):
T = current.T translations = TAG['']() strings = self._strings() if (self.translate and strings): append_translation = translations.append languages = [l for l in current.response.s3.l10n_languages if (l != 'en')] languages.insert(0, 'en') for language in languages: ...
'Constructor'
def __init__(self):
S3Method.__init__(self) self.log = S3SyncLog() self._config = None
'RESTful method handler, responds to: - GET [prefix]/[name]/sync.xml - incoming pull - PUT|POST [prefix]/[name]/sync.xml - incoming push - POST sync/repository/register.json - remote registration NB incoming pull/push reponse normally by local sync/sync controller as resource proxy => back-end generated...
def apply_method(self, r, **attr):
output = {} method = r.method if (method == 'sync'): if (r.http == 'GET'): output = self.__send(r, **attr) elif (r.http in ('PUT', 'POST')): output = self.__receive(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) elif (method == 'regist...
'Respond to an incoming registration request @param r: the S3Request @param attr: controller parameters for the request'
def __register(self, r, **attr):
from s3validators import JSONERRORS source = r.read_body() if (not source): r.error(400, 'Missing parameters') try: parameters = json.load(source[0]) except JSONERRORS: r.error(400, ('Invalid parameters: %s' % sys.exc_info()[1])) log = self.log result = log.S...
'Respond to an incoming pull @param r: the S3Request @param attr: the controller attributes'
def __send(self, r, **attr):
mixed = attr.get('mixed', False) get_vars = r.get_vars vars_get = get_vars.get resource = r.resource repository_uuid = vars_get('repository') connector = None if repository_uuid: rtable = current.s3db.sync_repository query = (rtable.uuid == repository_uuid) row = curr...
'Respond to an incoming push @param r: the S3Request @param attr: the controller attributes'
def __receive(self, r, **attr):
mixed = attr.get('mixed', False) get_vars = r.get_vars s3db = current.s3db db = current.db repository_uuid = get_vars.get('repository') connector = None if repository_uuid: rtable = s3db.sync_repository query = (rtable.uuid == repository_uuid) row = current.db(query)....
'Synchronize with a repository, called from scheduler task @param repository: the repository Row @return: True if successful, False if there was an error'
def synchronize(self, repository):
current.log.debug(('S3Sync: synchronize %s' % repository.url)) log = self.log repository_id = repository.id error = None if (repository.apitype == 'filesync'): if (not repository.path): error = 'No path set for repository' elif (not repository.url): ...
'Automatic conflict resolution @param item: the conflicting import item @param repository: the repository the item comes from @param resource: the resource the item shall be imported to'
@classmethod def onconflict(cls, item, repository, resource):
s3db = current.s3db _debug = current.log.debug tablename = resource.tablename resolver = s3db.get_config(tablename, 'onconflict') _debug(('Resolving conflict in %s' % resource.tablename)) _debug(('Repository: %s' % repository.name)) _debug(('Conflicting item: %s' % item)) ...
'Lazy access to the current sync config'
@property def config(self):
if (self._config is None): table = current.s3db.sync_config row = current.db().select(table.ALL, limitby=(0, 1)).first() self._config = row return self._config
'Read the current sync status'
def get_status(self):
table = current.s3db.sync_status row = current.db().select(table.ALL, limitby=(0, 1)).first() if (not row): row = Storage() return row
'Update the current sync status'
def set_status(self, **attr):
table = current.s3db.sync_status data = dict(((k, attr[k]) for k in attr if (k in table.fields))) data['timestmp'] = datetime.datetime.utcnow() row = current.db().select(table._id, limitby=(0, 1)).first() if row: row.update_record(**data) else: table.insert(**data) row = ...
'Get all filters for a synchronization task @param task_id: the task ID @return: a dict of dicts like {tablename: {url_var: value}}'
@staticmethod def get_filters(task_id):
db = current.db s3db = current.s3db ftable = s3db.sync_resource_filter query = ((ftable.task_id == task_id) & (ftable.deleted != True)) rows = db(query).select(ftable.tablename, ftable.filter_string) filters = {} for row in rows: tablename = row.tablename if (tablename in fil...
'RESTful method handler @param r: the S3Request instance @param attr: controller attributes for the request'
def apply_method(self, r, **attr):
output = dict() resource = r.resource if (resource.tablename == self.TABLENAME): return resource.crud.select(r, **attr) elif (resource.tablename == 'sync_repository'): pass elif r.interactive: here = ('%s.%s' % (r.controller, r.function)) sync_log = current.s3db[self....
'Writes a new entry to the log @param repository_id: the repository record ID @param resource_name: the resource name @param transmission: transmission mode (IN, OUT or None) @param mode: synchronization mode (PULL, PUSH or None) @param action: action that triggers the log entry (if any) @param result: the result of th...
@classmethod def write(cls, repository_id=None, resource_name=None, transmission=None, mode=None, action=None, result=None, remote=False, message=None):
if (result not in (cls.SUCCESS, cls.WARNING, cls.ERROR, cls.FATAL)): result = cls.SUCCESS if (result == cls.SUCCESS): remote = False if (transmission not in (cls.IN, cls.OUT)): transmission = cls.NONE if (mode not in (cls.PULL, cls.PUSH, cls.LOGIN, cls.REGISTER)): mode = ...
'S3SyncLog resource header'
@staticmethod def rheader(r, **attr):
if (r.id is None): return DIV(current.T('Showing latest entries first')) else: return None
'Constructor @param repository: the repository record (Row)'
def __init__(self, repository):
self.log = S3SyncLog self._config = None self.id = repository.id self.name = repository.name self.apitype = repository.apitype self.backend = repository.backend self.url = repository.url self.path = repository.path self.username = repository.username self.password = repository.pa...
'Lazy access to the current sync config'
@property def config(self):
if (self._config is None): table = current.s3db.sync_config row = current.db().select(table.ALL, limitby=(0, 1)).first() self._config = row return self._config
'Delegate other attributes and methods to the adapter @param name: the attribute/method'
def __getattr__(self, name):
return object.__getattribute__(self.adapter, name)
'Constructor @param repository: the repository (S3Repository instance)'
def __init__(self, repository):
self.repository = repository self.log = repository.log
'Register this site at the peer repository @return: True to indicate success, otherwise False'
def register(self):
raise NotImplementedError
'Login at the peer repository @return: None if successful, otherwise the error'
def login(self):
raise NotImplementedError
'Fetch updates from the peer repository and import them into the local database (active pull) @param task: the synchronization task (sync_task Row) @param onconflict: callback for automatic conflict resolution @return: tuple (error, mtime), with error=None if successful, else error=message, and mtime=modification times...
def pull(self, task, onconflict=None):
raise NotImplementedError
'Extract new updates from the local database and send them to the peer repository (active push) @param task: the synchronization task (sync_task Row) @return: tuple (error, mtime), with error=None if successful, else error=message, and mtime=modification timestamp of the youngest record sent'
def push(self, task):
raise NotImplementedError
'Respond to an incoming pull from the peer repository @param resource: the resource to be synchronized @param start: index of the first record to send @param limit: maximum number of records to send @param msince: minimum modification date/time for records to send @param filters: URL filters for record extraction @para...
def send(self, resource, start=None, limit=None, msince=None, filters=None, mixed=False):
raise NotImplementedError
'Respond to an incoming push from the peer repository @param source: the input stream (list of file-like objects) @param resource: the target resource @param strategy: the import strategy @param update_policy: the update policy @param conflict_policy: the conflict resolution policy @param onconflict: callback for confl...
def receive(self, source, resource, strategy=None, update_policy=None, conflict_policy=None, onconflict=None, last_sync=None, mixed=False):
raise NotImplementedError
'Entry point for REST interface @param r: the S3Request @param attr: controller attributes'
def apply_method(self, r, **attr):
if (r.http == 'GET'): if (r.representation == 'html'): output = self.tree(r, **attr) elif ((r.representation == 'json') and ('node' in r.get_vars)): output = self.node_json(r, **attr) elif (r.representation == 'xls'): output = self.export_xls(r, **attr) ...
'Page load @param r: the S3Request @param attr: controller attributes'
def tree(self, r, **attr):
output = {} tablename = self.resource.tablename widget_id = ('%s-hierarchy' % tablename) try: tree = self.render_tree(widget_id, record=r.record) except SyntaxError: r.error(405, ('No hierarchy configured for %s' % tablename)) if r.record: title = self.crud_st...
'Return a single node as JSON (id, parent and label) @param r: the S3Request @param attr: controller attributes'
def node_json(self, r, **attr):
resource = self.resource tablename = resource.tablename h = S3Hierarchy(tablename=tablename) if (not h.config): r.error(405, ('No hierarchy configured for %s' % tablename)) data = {} node_id = r.get_vars['node'] if node_id: try: node_id = long(node_id)...
'Render the tree @param widget_id: the widget ID @param record: the root record (if requested)'
def render_tree(self, widget_id, record=None):
resource = self.resource tablename = resource.tablename h = S3Hierarchy(tablename=tablename) if (not h.config): raise SyntaxError() root = None if record: try: root = record[h.pkey] except AttributeError as e: msg = ('S3Hierarchy: key %s n...
'Include JS & CSS needed for hierarchical CRUD'
@staticmethod def include_scripts(widget_id, widget_opts):
s3 = current.response.s3 scripts = s3.scripts theme = current.deployment_settings.get_ui_hierarchy_theme() script_dir = ('/%s/static/scripts' % current.request.application) if s3.debug: script = ('%s/jstree.js' % script_dir) if (script not in scripts): scripts.append(scri...
'Export nodes in the hierarchy in XLS format, including ancestor references. This is controlled by the hierarchy_export setting, which is a dict like: "field": "name", - the field name for the ancestor reference "root": "Organisation" - the label for the root level "branch": "Branch" - the label for the br...
def export_xls(self, r, **attr):
resource = self.resource tablename = resource.tablename h = S3Hierarchy(tablename=tablename) if (not h.config): r.error(405, ('No hierarchy configured for %s' % tablename)) setting = resource.get_config('hierarchy_export', {}) field = setting.get('field') if (not field): ...
'Constructor @param tablename: the tablename @param hierarchy: the hierarchy setting for the table (replaces the current setting) @param represent: a representation method for the node IDs @param filter: additional filter query for the table to select the relevant subset @param leafonly: filter strictly for leaf nodes'...
def __init__(self, tablename=None, hierarchy=None, represent=None, filter=None, leafonly=True):
self.tablename = tablename if hierarchy: current.s3db.configure(tablename, hierarchy=hierarchy) self.represent = represent self.filter = filter self.leafonly = leafonly self.__theset = None self.__flags = None self.__nodes = None self.__roots = None self.__pkey = None ...
'The raw nodes dict like: {<node_id>: {"p": <parent_id>, "c": <category>, "s": set(child nodes)'
@property def theset(self):
if (self.__theset is None): self.__connect() if self.__status('dirty'): self.read() return self.__theset
'Dict of status flags'
@property def flags(self):
if (self.__flags is None): theset = self.theset return self.__flags
'Hierarchy configuration of the target table'
@property def config(self):
tablename = self.tablename if tablename: s3db = current.s3db if ((tablename in current.db) or s3db.table(tablename, db_only=True)): return s3db.get_config(tablename, 'hierarchy') return None
'The nodes in the subset'
@property def nodes(self):
theset = self.theset if (self.__nodes is None): self.__subset() return self.__nodes
'The IDs of the root nodes in the subset'
@property def roots(self):
nodes = self.nodes return self.__roots
'The parent key'
@property def pkey(self):
if (self.__pkey is None): self.__keys() return self.__pkey
'The foreign key referencing the parent key'
@property def fkey(self):
if (self.__fkey is None): self.__keys() return self.__fkey
'The name of the link table containing the foreign key, or None if the foreign key is in the hierarchical table itself'
@property def link(self):
if (self.__link is DEFAULT): self.__keys() return self.__link
'The key in the link table referencing the child'
@property def lkey(self):
if (self.__lkey is DEFAULT): self.__keys() return self.__lkey
'The left join with the link table containing the foreign key'
@property def left(self):
if (self.__left is DEFAULT): self.__keys() return self.__left
'The category field'
@property def ckey(self):
if (self.__ckey is None): self.__keys() return self.__ckey
'Connect this instance to the hierarchy'
def __connect(self):
tablename = self.tablename if tablename: hierarchies = current.model.hierarchies if (tablename in hierarchies): hierarchy = hierarchies[tablename] self.__theset = hierarchy['nodes'] self.__flags = hierarchy['flags'] else: self.__theset = di...
'Check or update status flags @param flag: the name of the status flag to return @param default: the default value if the flag is not set @param attr: key-value pairs for flags to set @return: the value of the requested flag, or all flags as dict if no flag was specified'
def __status(self, flag=None, default=None, **attr):
flags = self.flags for (k, v) in attr.items(): if (v is not None): flags[k] = v else: flags.pop(k, None) if (flag is not None): return flags.get(flag, default) return flags
'Try loading the hierarchy from s3_hierarchy'
def load(self):
if (not self.config): return tablename = self.tablename if (not self.__status('dbstatus', True)): self.__status(dirty=True) return htable = current.s3db.s3_hierarchy query = (htable.tablename == tablename) row = current.db(query).select(htable.dirty, htable.hierarchy, lim...
'Save this hierarchy in s3_hierarchy'
def save(self):
if (not self.config): return tablename = self.tablename theset = self.theset if (not self.__status('dbupdate')): return nodes_dict = dict() for (node_id, node) in theset.items(): nodes_dict[node_id] = {'p': node['p'], 'c': node['c'], 's': (list(node['s']) if node['s'] els...
'Mark this hierarchy as dirty. To be called when the target table gets updated (can be called repeatedly). @param tablename: the tablename'
@classmethod def dirty(cls, tablename):
s3db = current.s3db if (not tablename): return config = s3db.get_config(tablename, 'hierarchy') if (not config): return hierarchies = current.model.hierarchies if (tablename in hierarchies): hierarchy = hierarchies[tablename] flags = hierarchy['flags'] else: ...
'Rebuild this hierarchy from the target table'
def read(self):
tablename = self.tablename if (not tablename): return s3db = current.s3db table = s3db[tablename] pkey = self.pkey fkey = self.fkey ckey = self.ckey fields = [pkey, fkey] if (ckey is not None): fields.append(table[ckey]) if ('deleted' in table): query = (t...
'Introspect the key fields in the hierarchical table'
def __keys(self):
tablename = self.tablename if (not tablename): return s3db = current.s3db table = s3db[tablename] config = s3db.get_config(tablename, 'hierarchy') if (not config): return if isinstance(config, tuple): (parent, self.__ckey) = config[:2] else: (parent, self....
'Pre-process a CRUD request to create a new node @param r: the request @param table: the hierarchical table @param parent_id: the parent ID'
def preprocess_create_node(self, r, parent_id):
table = current.s3db.table(self.tablename) query = (table[self.pkey.name] == parent_id) DELETED = current.xml.DELETED if (DELETED in table.fields): query &= (table[DELETED] != True) parent = current.db(query).select(table._id).first() if (not parent): raise KeyError('Parent re...
'Create a link table entry for a new node @param link: the link information (as returned from preprocess_create_node) @param node: the new node'
def postprocess_create_node(self, link, node):
try: node_id = node[self.pkey.name] except (AttributeError, KeyError): return s3db = current.s3db tablename = link['linktable'] linktable = s3db.table(tablename) if (not linktable): return lkey = link['lkey'] rkey = link['rkey'] data = {rkey: link['parent_id']...
'Recursive deletion of hierarchy branches @param node_ids: the parent node IDs of the branches to be deleted @param cascade: cascade call, do not commit (internal use) @return: number of deleted nodes, or None if cascade failed'
def delete(self, node_ids, cascade=False):
if (not self.config): return None tablename = self.tablename total = 0 for node_id in node_ids: children = self.children(node_id) if children: result = self.delete(children, cascade=True) if (result is None): if (not cascade): ...
'Add a new node to the hierarchy @param node_id: the node ID @param parent_id: the parent node ID @param category: the category'
def add(self, node_id, parent_id=None, category=None):
theset = self.__theset if (node_id in theset): node = theset[node_id] if (category is not None): node['c'] = category elif node_id: node = {'s': set(), 'c': category} else: raise SyntaxError if parent_id: if (parent_id not in theset): p...
'Remove a node from the hierarchy @param node_id: the node ID'
def remove(self, node_id):
theset = self.__theset if (node_id in theset): node = theset[node_id] else: return False parent_id = node['p'] if parent_id: parent = theset[parent_id] parent['s'].discard(node_id) del theset[node_id] return True
'Generate the subset of accessible nodes which match the filter'
def __subset(self):
theset = self.theset roots = set() subset = {} resource = current.s3db.resource(self.tablename, filter=self.filter) pkey = self.pkey rows = resource.select([pkey.name], as_rows=True) if rows: key = str(pkey) if self.leafonly: ids = set() for row in row...
'Get the category of a node @param node_id: the node ID @return: the node category'
def category(self, node_id):
node = self.nodes.get(node_id) if (not node): return None else: return node['c']
'Get the parent node of a node @param node_id: the node ID @param classify: return the root node as tuple (id, category) instead of just id @return: the root node ID (or tuple (id, category), respectively)'
def parent(self, node_id, classify=False):
nodes = self.nodes default = ((None, None) if classify else None) node = nodes.get(node_id) if (not node): return default parent_id = node['p'] if (not parent_id): return default parent_node = nodes.get(parent_id) if (not parent_node): return default parent_ca...
'Get child nodes of a node @param node_id: the node ID @param category: return only children of this category @param classify: return each node as tuple (id, category) instead of just ids @return: the child nodes as Python set'
def children(self, node_id, category=DEFAULT, classify=False):
nodes = self.nodes default = set() node = nodes.get(node_id) if (not node): return default child_ids = node['s'] if (not child_ids): return default children = set() for child_id in child_ids: child_node = nodes.get(child_id) if (not child_node): ...
'Return the ancestor path of a node @param node_id: the node ID @param category: start with this category rather than with root @param classify: return each node as tuple (id, category) instead of just ids @return: the path as list, starting at the root node'
def path(self, node_id, category=DEFAULT, classify=False):
nodes = self.nodes node = nodes.get(node_id) if (not node): return [] this = ((node_id, node['c']) if classify else node_id) if ((category is not DEFAULT) and (node['c'] == category)): return [this] parent_id = node['p'] if (not parent_id): return [this] path = se...
'Get the root node for a node. Returns the node if it is the root node itself. @param node_id: the node ID @param category: find the closest node of this category rather than the absolute root @param classify: return the root node as tuple (id, category) instead of just id @return: the root node ID (or tuple (id, categ...
def root(self, node_id, category=DEFAULT, classify=False):
nodes = self.nodes default = ((None, None) if classify else None) node = nodes.get(node_id) if (not node): return default this = ((node_id, node['c']) if classify else node_id) if ((category is not DEFAULT) and (node['c'] == category)): return this parent_id = node['p'] i...
'Determine the depth of a hierarchy @param node_id: the start node (default to all root nodes)'
def depth(self, node_id, level=0):
nodes = self.nodes depth = self.depth node = nodes.get(node_id) if (not node): roots = self.roots result = max((depth(root) for root in roots)) else: children = node['s'] if children: result = max((depth(n, level=(level + 1)) for n in children)) el...
'Get the sibling nodes of a node. If the node is a root node, this method returns all root nodes. @param node_id: the node ID @param category: return only nodes of this category @param classify: return each node as tuple (id, category) instead of just id @param inclusive: include the start node @param return: a set of ...
def siblings(self, node_id, category=DEFAULT, classify=False, inclusive=False):
result = set() nodes = self.nodes node = nodes.get(node_id) if (not node): return result parent_id = node['p'] if (not parent_id): siblings = [(k, nodes[k]) for k in self.roots] else: parent = nodes[parent_id] if parent['s']: siblings = [(k, nodes[...
'Find descendant nodes of a node @param node_id: the node ID (can be an iterable of node IDs) @param category: find nodes of this category @param classify: return each node as tuple (id, category) instead of just ids @param inclusive: include the start node(s) if they match @return: a set of node IDs (or tuples (id, ca...
def findall(self, node_id, category=DEFAULT, classify=False, inclusive=False):
result = set() findall = self.findall if isinstance(node_id, (set, list, tuple)): for n in node_id: if (n is None): continue result |= findall(n, category=category, classify=classify, inclusive=inclusive) return result nodes = self.nodes node =...
'Represent nodes as labels, the labels are stored in the nodes as attribute "l". @param node_ids: the node IDs (None for all nodes) @param renderer: the representation method (falls back to the "name" field in the target table if present)'
def _represent(self, node_ids=None, renderer=None):
theset = self.theset LABEL = 'l' if (node_ids is None): node_ids = self.nodes.keys() pending = set() for node_id in node_ids: node = theset.get(node_id) if (not node): continue if (LABEL not in node): pending.add(node_id) if (renderer is No...
'Get a label for a node @param node_id: the node ID @param represent: the node ID representation method'
def label(self, node_id, represent=None):
LABEL = 'l' theset = self.theset node = theset.get(node_id) if node: if (LABEL in node): label = node[LABEL] else: self._represent(node_ids=[node_id], renderer=represent) if (LABEL in node): label = node[LABEL] if (type(label) is unicod...
'Render this hierarchy as nested unsorted list @param widget_id: a unique ID for the HTML widget @param root: node ID of the start node (defaults to all available root nodes) @param represent: the representation method for the node IDs @param hidden: render with style display:none @param _class: the HTML class for the ...
def html(self, widget_id, root=None, represent=None, hidden=True, none=None, _class=None):
self._represent(renderer=represent) roots = ([root] if root else self.roots) html = self._html output = UL([html(node_id, widget_id, represent=represent) for node_id in roots], _id=widget_id, _style=('display:none' if hidden else None)) if _class: output.add_class(_class) if none: ...
'Recursively render a node as list item (with subnodes as unsorted list inside the item) @param node_id: the node ID @param widget_id: the unique ID for the outermost list @param represent: the node ID representation method @return: the list item (LI) @todo: option to add CRUD permissions'
def _html(self, node_id, widget_id, represent=None):
node = self.nodes.get(node_id) if (not node): return None label = self.label(node_id, represent=represent) if (label is None): label = s3_unicode(node_id) subnodes = node['s'] item = LI(label, _id=('%s-%s' % (widget_id, node_id)), _rel=('parent' if subnodes else 'leaf'), _class='...
'Export the hierarchy beneath a node @param node_id: the root node @param prefix: prefix for the hierarchy column in the output @param depth: the maximum depth to export @param level: the current recursion level (internal) @param path: the path dict for this node (internal) @param hcol: the hierarchy column in the inpu...
def export_node(self, node_id, prefix='_hierarchy', depth=None, level=0, path=None, hcol=None, columns=None, data=None, node_list=None):
if (node_list is None): node_list = [] if ((depth is not None) and (level > depth)): return node_list node = self.nodes.get(node_id) if (not node): return node_list if data: if (node_id not in data): return node_list node_data = data.get(node_id) ...
'Constructor'
def __init__(self):
self.domain = current.request.env.server_name self.error = None self.filter_mci = False self.show_ids = False self.show_urls = True
'Parse an XML source into an element tree @param source: the XML source - can be a file-like object, a filename or a HTTP/HTTPS/FTP URL'
def parse(self, source):
self.error = None if (isinstance(source, basestring) and (source[:5] == 'https')): try: source = urllib2.urlopen(source) except: self.error = ('XML Source error: %s' % sys.exc_info()[1]) return None try: parser = etree.XMLParser(no_network...
'Transform an element tree with XSLT @param tree: the element tree @param stylesheet_path: pathname of the XSLT stylesheet @param args: dict of arguments to pass to the stylesheet'
def transform(self, tree, stylesheet_path, **args):
self.error = None if args: _args = dict(((k, ("'%s'" % args[k])) for k in args)) else: _args = None if isinstance(stylesheet_path, (etree._ElementTree, etree._Element)): stylesheet = stylesheet_path else: stylesheet = self.parse(stylesheet_path) if (stylesheet is ...
'Wraps XML contents into an XML envelope like: <contents> <object> <description>Description Text</description> <-- tree gets copied in here --> </object> <!-- can be multiple <object> elements --> </contents> @param tree: the element tree or list of trees to wrap, can also be a list of tuples (tree, description) in ord...
def envelope(self, tree, stylesheet_path, **args):
if (not isinstance(tree, (list, tuple))): tree = [tree] root = etree.Element(self.TAG.contents) for subtree in tree: contentDescription = None if isinstance(subtree, (list, tuple)): contentObject = subtree[0] if (len(subtree) > 1): contentDescr...
'Convert an element tree into XML as string @param tree: the element tree @param xml_declaration: add an XML declaration to the output @param pretty_print: provide pretty formatted output'
@staticmethod def tostring(tree, xml_declaration=True, pretty_print=True):
return etree.tostring(tree, xml_declaration=xml_declaration, encoding='utf-8', pretty_print=pretty_print)
'Builds a S3XML tree from a list of elements @param elements: list of <resource> elements @param root: the root element to link the tree to @param domain: name of the current domain @param url: url of the request @param start: the start record (in server-side pagination) @param limit: the page size (in server-side pagi...
def tree(self, elements, root=None, domain=None, url=None, start=None, limit=None, results=None, maxbounds=False):
ATTRIBUTE = self.ATTRIBUTE success = False if (root is None): root = etree.Element(self.TAG.root) if ((elements is not None) or len(root)): success = True set_attribute = root.set set_attribute(ATTRIBUTE.success, json.dumps(success)) if (start is not None): set_attrib...
'Exports UIDs with domain prefix @param uid: the UID'
def export_uid(self, uid):
if (not uid): return uid if (uid[:4] == 'urn:'): return uid else: domain = self.domain if (domain and ('/' not in uid[1:(-1)])): return ('%s/%s' % (domain, uid.strip('/'))) else: return uid
'Imports UIDs with domain prefixes @param uid: the UID'
def import_uid(self, uid):
domain = self.domain if ((not uid) or uid.startswith('urn:') or (not domain)): return uid elif ('/' in uid[1:(-1)]): (_domain, _uid) = uid.strip('/').split('/', 1) if (_domain == domain): return _uid else: return uid else: return uid
'Get the representation of a field value @param table: the database table @param f: the field name @param v: the value'
def represent(self, table, f, v):
if (f in (self.CUSER, self.MUSER, self.OUSER)): represent = current.cache.ram(('auth_user_%s' % v), (lambda : self.represent_user(v)), time_expire=60) elif (f in self.OGROUP): represent = current.cache.ram(('auth_group_%s' % v), (lambda : self.represent_role(v)), time_expire=60) else: ...
'Generates a reference map for a record @param table: the database table @param record: the record @param fields: list of reference field names in this table'
def rmap(self, table, record, fields):
reference_map = [] DELETED = self.DELETED REPLACEDBY = self.REPLACEDBY if ((DELETED in record) and record[DELETED] and (REPLACEDBY in record) and record[REPLACEDBY]): fields = [REPLACEDBY] else: fields = [f for f in fields if ((f in record) and record[f])] if (not fields): ...
'Adds <reference> elements to a <resource> @param element: the <resource> element @param rmap: the reference map for the corresponding record @param show_ids: insert the record ID as attribute in references'
def add_references(self, element, rmap, show_ids=False, lazy=None):
REFERENCE = self.TAG.reference ATTRIBUTE = self.ATTRIBUTE RESOURCE = ATTRIBUTE.resource FIELD = ATTRIBUTE.field VALUE = ATTRIBUTE.value ID = ATTRIBUTE.id RB = ATTRIBUTE.replaced_by UID = self.UID REPLACEDBY = self.REPLACEDBY as_json = json.dumps SubElement = etree.SubElement ...
'Add lat/lon to location references @param rmap: the reference map of the tree'
def latlon(self, rmap):
ATTRIBUTE = self.ATTRIBUTE locations = {} for reference in rmap: if ((reference.table == 'gis_location') and (len(reference.id) == 1)): location_id = reference.id[0] if (location_id not in locations): locations[location_id] = [reference] else: ...
'GIS-encodes the master resource so that it can be transformed into a mappable format. @param resource: the referencing resource @param record: the particular record @param element: the XML element @param location_data: dictionary of location data from gis.get_location_data() @ToDo: Support multiple locations per maste...
def gis_encode(self, resource, record, element, location_data={}):
format = current.auth.permission.format if (format not in ('geojson', 'georss', 'gpx', 'kml')): return tablename = resource.tablename if (tablename == 'gis_feature_query'): return gis = current.gis request = current.request settings = current.deployment_settings ATTRIBUTE...
'Creates a <resource> element from a record @param parent: the parent element in the document tree @param table: the database table @param record: the record @param alias: the resource alias (for disambiguation of components) @param fields: list of field names to include @param url: URL of the record @param lazy: lazy ...
def resource(self, parent, table, record, alias=None, fields=[], url=None, lazy=None, postprocess=None):
SubElement = etree.SubElement UID = self.UID MCI = self.MCI DELETED = self.DELETED TAG = self.TAG RESOURCE = TAG['resource'] DATA = TAG['data'] ATTRIBUTE = self.ATTRIBUTE NAME = ATTRIBUTE['name'] ALIAS = ATTRIBUTE['alias'] FIELD = ATTRIBUTE['field'] VALUE = ATTRIBUTE['val...
'Selects resources from an element tree @param tree: the element tree @param tablename: table name to search for'
@classmethod def select_resources(cls, tree, tablename):
resources = [] if isinstance(tree, etree._ElementTree): root = tree.getroot() if ((root is None) or (root.tag != cls.TAG.root)): return resources else: root = tree if ((root is None) or (not len(root))): return resources expr = ('./%s[@%s="%s"]' % (cls.TAG...
'Selects component elements in a resource element'
@classmethod def components(cls, element, names=None):
RESOURCE = cls.TAG.resource NAME = cls.ATTRIBUTE.name for child in element.iterchildren(): if (child.tag == RESOURCE): if ((names is None) or (child.get(NAME, None) in names)): (yield child) return