desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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):
xml = current.xml _debug = current.log.debug repository = self.repository log = repository.log resource_name = task.resource_name _debug(('S3SyncCiviCRM.push(%s, %s)' % (repository.url, resource_name))) result = log.FATAL remote = False message = 'Push to CiviCRM currentl...
'Register this site at the peer repository @return: True to indicate success, otherwise False'
def register(self):
return True
'Login at the peer repository @return: None if successful, otherwise the error'
def login(self):
repository = self.repository url = repository.url error = None if (not url): error = 'Remote URL required for FTP Push' else: import ftplib try: ftp_connection = ftplib.FTP(url) except ftplib.all_errors: error = sys.exc_info()[1]...
'Fetch updates from the repository and import them into the local database (Active Pull) @param task: the task (sync_task Row)'
def pull(self, task, onconflict=None):
repository = self.repository message = 'Pull from FTP currently not supported' log = repository.log log.write(repository_id=repository.id, resource_name=task.resource_name, transmission=log.OUT, mode=log.PULL, action=None, remote=False, result=log.FATAL, message=message) return (messa...
'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):
repository = self.repository resource_name = task.resource_name log = repository.log remote = False output = None current.log.debug(('S3SyncRepository.push(%s, %s)' % (repository.url, resource_name))) resource = current.s3db.resource(resource_name) filters = current.sync.get_filters(t...
'Returns the representation data for the resource'
def _get_data(self, resource, representation):
request = S3Request(prefix=resource.prefix, name=resource.name, extension=representation) if request.transformable(): return resource.export_xml(stylesheet=request.stylesheet(), pretty_print=True) else: if (representation == 'csv'): exporter = S3Exporter().csv elif (repre...
'Constructor'
def __init__(self, repository):
super(S3SyncAdapter, self).__init__(repository) self.access_token = None self.token_type = None
'Register at the repository, in Wrike: use client ID and the authorization code (site key), alternatively username and password to obtain the refresh_token and store it in the repository config. @note: this invalidates the authorization code (if any), so it will be set to None regardless whether this operation succeeds...
def register(self):
repository = self.repository log = repository.log success = False remote = False skip = False data = None site_key = repository.site_key if (not site_key): username = repository.username password = repository.password if (username and password): data =...
'Login to the repository, in Wrike: use the client ID (username), the client secret (password) and the refresh token to obtain the access token for subsequent requests. @return: None if successful, otherwise error message'
def login(self):
repository = self.repository log = repository.log error = None remote = False refresh_token = repository.refresh_token if (not refresh_token): result = log.FATAL error = 'Login failed: no refresh token available (registration failed?)' else: data ...
'Pull updates from this repository @param task: the task Row @param onconflict: synchronization conflict resolver @return: tuple (error, mtime), with error=None if successful, else error=message, and mtime=modification timestamp of the youngest record received'
def pull(self, task, onconflict=None):
repository = self.repository resource_name = task.resource_name current.log.debug(('S3SyncWrike.pull(%s, %s)' % (repository.url, resource_name))) xml = current.xml log = repository.log last_pull = task.last_pull if (last_pull and (task.update_policy not in ('THIS', 'OTHER'))): msi...
'Push data for a task @param task: the 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):
error = 'Wrike API push not implemented' current.log.error(error) return (error, None)
'Get all accessible accounts @return: dict {account_id: (rootFolderId, recycleBinId)}'
def fetch_accounts(self, root):
(response, message) = self._send_request(path='accounts') if (not response): return (None, message) accounts = {} data = response.get('data') if (data and (type(data) is list)): SubElement = etree.SubElement for account_data in data: account_id = account_data.get(...
'Fetch folders from a Wrike account and add them to the data tree @param root: the root element of the data tree @param account_id: the Wrike account ID'
def fetch_folders(self, root, account_id):
(response, message) = self._send_request(path=('accounts/%s/folders' % account_id)) if (not response): return (None, message) folders = {} data = response.get('data') if (data and (type(data) is list)): SubElement = etree.SubElement for folder_data in data: scope ...
'Fetch all tasks in a folder @param root: the root element of the data tree @param folder_id: the ID of the folder to read from @param deleted: mark the tasks as deleted in the data tree (when reading tasks from a recycle bin) @param msince: only retrieve tasks that have been modified after this date/time (ISO-formatte...
def fetch_tasks(self, root, folder_id, deleted=False, msince=None):
fields = json.dumps(['parentIds', 'description']) args = {'descendants': 'true', 'fields': json.dumps(['parentIds', 'description'])} if (msince is not None): args['updatedDate'] = ('%sZ,' % msince) (response, message) = self._send_request(path=('folders/%s/tasks' % folder_id), args=args) if ...
'Recursively convert the nested task details dicts into SubElements @param task: the task Element @param data: the nested dict @param keys: the mapping of dict keys to SubElement names'
@classmethod def add_details(cls, task, data, keys):
if (not isinstance(data, dict)): return SubElement = etree.SubElement for (key, name) in keys.items(): wrapper = data.get(key) if (wrapper is None): continue if isinstance(name, dict): cls.add_details(task, wrapper, name) else: deta...
'Store the current refresh token in the db, also invalidated the site_key (authorization code) because it can not be used again.'
def update_refresh_token(self):
repository = self.repository repository.site_key = None table = current.s3db.sync_repository current.db((table.id == repository.id)).update(refresh_token=repository.refresh_token, site_key=repository.site_key) return
'Send a request to the Wrike API @param method: the HTTP method @param path: the path relative to the repository URL @param data: the data to send @param auth: this is an authorization request'
def _send_request(self, method='GET', path=None, args=None, data=None, auth=False):
repository = self.repository api = ('oauth2/token' if auth else 'api/v3') url = '/'.join((repository.url.rstrip('/'), api)) if path: url = '/'.join((url, path.lstrip('/'))) if args: url = '?'.join((url, urllib.urlencode(args))) req = urllib2.Request(url=url) handlers = [] ...
'Register this site at the peer repository @return: True to indicate success, otherwise False'
def register(self):
repository = self.repository if (not repository.url): return True url = ('%s/sync/repository/register.json' % repository.url) current.log.debug(('S3Sync: register at %s' % url)) config = repository.config name = current.deployment_settings.get_base_public_url().split('//', 1)[1]...
'Login at the peer repository @return: None if successful, otherwise the error'
def login(self):
return None
'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):
_debug = current.log.debug repository = self.repository xml = current.xml config = repository.config resource_name = task.resource_name _debug(('S3Sync: pull %s from %s' % (resource_name, repository.url))) url = ('%s/sync/sync.xml?resource=%s&repository=%s' % (repository.url, res...
'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):
xml = current.xml _debug = current.log.debug repository = self.repository config = repository.config resource_name = task.resource_name _debug(('S3SyncRepository.push(%s, %s)' % (repository.url, resource_name))) url = ('%s/sync/sync.xml?resource=%s&repository=%s' % (repository.url, resour...
'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, pretty_print=False):
if ((not resource) or mixed): msg = 'Mixed resource synchronization not supported' return {'status': self.log.FATAL, 'message': msg, 'response': current.xml.json_message(False, 400, msg)} output = resource.export_xml(start=start, limit=limit, filters=filters, msince=msince, pretty_pr...
'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):
if ((not resource) or mixed): msg = 'Mixed resource synchronization not supported' return {'status': self.log.FATAL, 'remote': False, 'message': msg, 'response': current.xml.json_message(False, 400, msg)} repository = self.repository ignore_errors = True if onconflict: ...
'1st Stage Parser - called by msg.parse() Sets the appropriate Authorisation level and then calls the parser function from the template'
@staticmethod def parser(function_name, message_id, **kwargs):
reply = None s3db = current.s3db table = s3db.msg_message message = current.db((table.message_id == message_id)).select(limitby=(0, 1)).first() from_address = message.from_address if ('<' in from_address): from_address = from_address.split('<')[1].split('>')[0] email = S3Parsing.is_s...
'Authenticate a login request'
@staticmethod def parse_login(message):
if ((not message) or (not message.body)): return (None, None) words = message.body.split(' ') login = False email = None password = None if ('LOGIN' in [word.upper() for word in words]): login = True if ((len(words) == 2) and login): password = words[1] elif ((...
'Check whether there is an alive session from the same sender'
@staticmethod def is_session_alive(from_address):
email = None now = current.request.utcnow stable = current.s3db.msg_session query = ((stable.is_expired == False) & (stable.from_address == from_address)) records = current.db(query).select(stable.id, stable.created_datetime, stable.expiration_time, stable.email) for record in records: t...
'Lookup a Person from an Email Address'
@staticmethod def lookup_person(address):
s3db = current.s3db if ('<' in address): address = address.split('<')[1].split('>')[0] ptable = s3db.pr_person ctable = s3db.pr_contact query = (((((ctable.value == address) & (ctable.contact_method == 'EMAIL')) & (ctable.pe_id == ptable.pe_id)) & (ptable.deleted == False)) & (ctable.deleted...
'Lookup a Human Resource from an Email Address'
@staticmethod def lookup_human_resource(address):
db = current.db s3db = current.s3db if ('<' in address): address = address.split('<')[1].split('>')[0] hrtable = s3db.hrm_human_resource ptable = db.pr_person ctable = s3db.pr_contact query = (((((((ctable.value == address) & (ctable.contact_method == 'EMAIL')) & (ctable.pe_id == pta...
'Constructor @param tablename: tablename, Table, or an S3Resource instance @param prefix: prefix to use for the tablename @param id: record ID (or list of record IDs) @param uid: record UID (or list of record UIDs) @param filter: filter query @param vars: dictionary of URL query variables @param components: list of com...
def __init__(self, tablename, id=None, prefix=None, uid=None, filter=None, vars=None, parent=None, linked=None, linktable=None, alias=None, components=None, filter_component=None, include_deleted=False, approved=True, unapproved=False, context=False, extra_filters=None):
s3db = current.s3db auth = current.auth table = None table_alias = None if (prefix is None): if (not isinstance(tablename, basestring)): if isinstance(tablename, Table): table = tablename table_alias = table._tablename tablename = t...
'Attach a component @param alias: the alias @param hook: the hook'
def _attach(self, alias, hook):
filterby = hook.filterby if ((alias is not None) and (filterby is not None)): table_alias = ('%s_%s_%s' % (hook.prefix, hook.alias, hook.name)) table = hook.table.with_alias(table_alias) table._id = table[table._id.name] hook.table = table else: table_alias = None ...
'Query builder @param id: record ID or list of record IDs to include @param uid: record UID or list of record UIDs to include @param filter: filtering query (DAL only) @param vars: dict of URL query variables @param extra_filters: extra filters (to be applied on pre-filtered subsets), as list of tuples (method, express...
def build_query(self, id=None, uid=None, filter=None, vars=None, extra_filters=None, filter_component=None):
self._length = None self.rfilter = S3ResourceFilter(self, id=id, uid=uid, filter=filter, vars=vars, extra_filters=extra_filters, filter_component=filter_component) return self.rfilter
'Extend the current resource filter @param f: a Query or a S3ResourceQuery instance @param c: alias of the component this filter concerns, automatically adds the respective component join (not needed for S3ResourceQuery instances)'
def add_filter(self, f=None, c=None):
if (f is None): return self.clear() if (self.rfilter is None): self.rfilter = S3ResourceFilter(self) self.rfilter.add_filter(f, component=c)
'Extend the resource filter of a particular component, does not affect the master resource filter (as opposed to add_filter) @param alias: the alias of the component @param f: a Query or a S3ResourceQuery instance'
def add_component_filter(self, alias, f=None):
if (f is None): return if (self.rfilter is None): self.rfilter = S3ResourceFilter(self) self.rfilter.add_filter(f, component=alias, master=False)
'And an extra filter (to be applied on pre-filtered subsets) @param method: a name of a known filter method, or a callable filter method @param expression: the filter expression (string)'
def add_extra_filter(self, method, expression):
self.clear() if (self.rfilter is None): self.rfilter = S3ResourceFilter(self) self.rfilter.add_extra_filter(method, expression)
'Replace the current extra filters @param filters: list of tuples (method, expression), or None to remove all extra filters'
def set_extra_filters(self, filters):
self.clear() if (self.rfilter is None): self.rfilter = S3ResourceFilter(self) self.rfilter.set_extra_filters(filters)
'Get the effective query @return: Query'
def get_query(self):
if (self.rfilter is None): self.build_query() return self.rfilter.get_query()
'Get the effective virtual filter @return: S3ResourceQuery'
def get_filter(self):
if (self.rfilter is None): self.build_query() return self.rfilter.get_filter()
'Remove the current query (does not remove the set!)'
def clear_query(self):
self.rfilter = None components = self.components if components: for c in components: components[c].clear_query()
'Get the total number of available records in this resource @param left: left outer joins, if required @param distinct: only count distinct rows'
def count(self, left=None, distinct=False):
if (self.rfilter is None): self.build_query() if (self._length is None): self._length = self.rfilter.count(left=left, distinct=distinct) return self._length
'Extract data from this resource @param fields: the fields to extract (selector strings) @param start: index of the first record @param limit: maximum number of records @param left: additional left joins required for filters @param orderby: orderby-expression for DAL @param groupby: fields to group by (overrides fields...
def select(self, fields, start=0, limit=None, left=None, orderby=None, groupby=None, distinct=False, virtual=True, count=False, getids=False, as_rows=False, represent=False, show_links=True, raw_data=False):
data = S3ResourceData(self, fields, start=start, limit=limit, left=left, orderby=orderby, groupby=groupby, distinct=distinct, virtual=virtual, count=count, getids=getids, as_rows=as_rows, represent=represent, show_links=show_links, raw_data=raw_data) if as_rows: return data.rows else: return...
'Insert a record into this resource @param fields: dict of field/value pairs to insert'
def insert(self, **fields):
table = self.table tablename = self.tablename authorised = current.auth.s3_has_permission('create', tablename) if (not authorised): from s3error import S3PermissionError raise S3PermissionError(('Operation not permitted: INSERT INTO %s' % tablename)) record_id = self.t...
'Delete all (deletable) records in this resource @param format: the representation format of the request (optional) @param cascade: this is a cascade delete (prevents rollbacks/commits) @param replaced_by: used by record merger @return: number of records deleted'
def delete(self, format=None, cascade=False, replaced_by=None):
s3db = current.s3db self.error = None permission_error = False tablename = self.tablename table = self.table table_fields = table.fields get_config = self.get_config pkey = self._id.name fields = [pkey] add_field = fields.append supertables = get_config('super_entity') if...
'Approve all records in this resource @param components: list of component aliases to include, None for no components, empty list or tuple to approve all components (default) @param approve: set to approved (False to reset to unapproved) @param approved_by: set approver explicitly, a valid auth_user.id or 0 for approva...
def approve(self, components=(), approve=True, approved_by=None):
if ('approved_by' not in self.fields): return True auth = current.auth if approve: if (approved_by is None): user = auth.user if user: user_id = user.id else: return False else: user_id = approved_by ...
'Reject (delete) all records in this resource'
def reject(self, cascade=False):
db = current.db s3db = current.s3db define_resource = s3db.resource DELETED = current.xml.DELETED INTEGRITY_ERROR = current.ERROR.INTEGRITY_ERROR tablename = self.tablename table = self.table pkey = table._id.name get_config = s3db.get_config ondelete = get_config(tablename, 'ond...
'Merge two records, see also S3RecordMerger.merge'
def merge(self, original_id, duplicate_id, replace=None, update=None, main=True):
from s3merge import S3RecordMerger return S3RecordMerger(self).merge(original_id, duplicate_id, replace=replace, update=update, main=main)
'Generate a data table of this resource @param fields: list of fields to include (field selector strings) @param start: index of the first record to include @param limit: maximum number of records to include @param left: additional left joins for DB query @param orderby: orderby for DB query @param distinct: distinct-f...
def datatable(self, fields=None, start=0, limit=None, left=None, orderby=None, distinct=False, getids=False):
if (fields is None): fields = [f.name for f in self.readable_fields()] selectors = list(fields) table = self.table table_id = table._id pkey = table_id.name if (pkey not in selectors): fields.insert(0, pkey) selectors.insert(0, pkey) id_repr = table_id.represent t...
'Generate a data list of this resource @param fields: list of fields to include (field selector strings) @param start: index of the first record to include @param limit: maximum number of records to include @param left: additional left joins for DB query @param orderby: orderby for DB query @param distinct: distinct-fl...
def datalist(self, fields=None, start=0, limit=None, left=None, orderby=None, distinct=False, getids=False, list_id=None, layout=None):
if (fields is None): fields = [f.name for f in self.readable_fields()] selectors = list(fields) table = self.table pkey = table._id.name if (pkey not in selectors): fields.insert(0, pkey) selectors.insert(0, pkey) data = self.select(selectors, start=start, limit=limit, or...
'Export a JSON representation of the resource. @param fields: list of field selector strings @param start: index of the first record @param limit: maximum number of records @param left: list of (additional) left joins @param distinct: select only distinct rows @param orderby: Orderby-expression for the query @return: t...
def json(self, fields=None, start=0, limit=None, left=None, distinct=False, orderby=None):
data = self.select(fields=fields, start=start, limit=limit, orderby=orderby, left=left, distinct=distinct)['rows'] return json.dumps(data)
'Loads records from the resource, applying the current filters, and stores them in the instance. @param fields: list of field names to include @param skip: list of field names to skip @param start: the index of the first record to load @param limit: the maximum number of records to load @param orderby: orderby-expressi...
def load(self, fields=None, skip=None, start=None, limit=None, orderby=None, virtual=True, cacheable=False):
table = self.table tablename = self.tablename UID = current.xml.UID load_uids = hasattr(table, UID) if (not skip): skip = tuple() if (fields or skip): s3 = current.response.s3 if ('all_meta_fields' in s3): meta_fields = s3.all_meta_fields else: ...
'Removes the records currently stored in this instance'
def clear(self):
self._rows = None self._rowindex = None self._length = None self._ids = None self._uids = None self.files = Storage() if self.components: for c in self.components: self.components[c].clear()
'Get the current set as Rows instance @param fields: the fields to include (list of Fields)'
def records(self, fields=None):
if (fields is None): if (self.tablename == 'gis_location'): fields = [f for f in self.table if (f.name not in ('wkt', 'the_geom'))] else: fields = [f for f in self.table] if (self._rows is None): return Rows(current.db) else: colnames = map(str, fields...
'Find a record currently stored in this instance by its record ID @param key: the record ID @return: a Row @raises: IndexError if the record is not currently loaded'
def __getitem__(self, key):
index = self._rowindex if (index is None): _id = self._id.name rows = self._rows if rows: index = Storage([(str(row[_id]), row) for row in rows]) else: index = Storage() self._rowindex = index key = str(key) if (key in index): retur...
'Iterate over the records currently stored in this instance'
def __iter__(self):
if (self._rows is None): self.load() rows = self._rows for i in xrange(len(rows)): (yield rows[i]) return
'Get component records for a record currently stored in this instance. @param key: the record ID @param component: the name of the component @param link: the name of the link table @return: a Row (if component is None) or a list of rows'
def get(self, key, component=None, link=None):
if (not key): raise KeyError('Record not found') if (self._rows is None): self.load() try: master = self[key] except IndexError: raise KeyError('Record not found') if ((not component) and (not link)): return master elif link: if (link i...
'Get the IDs of all records currently stored in this instance'
def get_id(self):
if (self._ids is None): self.__load_ids() if (not self._ids): return None elif (len(self._ids) == 1): return self._ids[0] else: return self._ids
'Get the UUIDs of all records currently stored in this instance'
def get_uid(self):
if (current.xml.UID not in self.table.fields): return None if (self._ids is None): self.__load_ids() if (not self._uids): return None elif (len(self._uids) == 1): return self._uids[0] else: return self._uids
'The number of currently loaded rows'
def __len__(self):
if (self._rows is not None): return len(self._rows) else: return 0
'Loads the IDs/UIDs of all records matching the current filter'
def __load_ids(self):
table = self.table UID = current.xml.UID pkey = table._id.name if (UID in table.fields): has_uid = True fields = (pkey, UID) else: has_uid = False fields = (pkey,) rfilter = self.rfilter multiple = (rfilter.multiple if (rfilter is not None) else True) if (...
'String representation of this resource'
def __repr__(self):
pkey = self.table._id.name if self._rows: ids = [r[pkey] for r in self] return ('<S3Resource %s %s>' % (self.tablename, ids)) else: return ('<S3Resource %s>' % self.tablename)
'Tests whether this resource contains a (real) field. @param item: the field selector or Field instance'
def __contains__(self, item):
fn = str(item) if ('.' in fn): (tn, fn) = fn.split('.', 1) if (tn == self.tablename): item = fn try: rf = self.resolve_selector(str(item)) except (SyntaxError, AttributeError): return 0 if (rf.field is not None): return 1 else: return 0...
'Boolean test of this resource'
def __nonzero__(self):
return (self is not None)
'Export this resource as S3XML @param start: index of the first record to export (slicing) @param limit: maximum number of records to export (slicing) @param msince: export only records which have been modified after this datetime @param fields: data fields to include (default: all) @param dereference: include referenc...
def export_xml(self, start=None, limit=None, msince=None, fields=None, dereference=True, maxdepth=MAXDEPTH, mcomponents=[], rcomponents=None, references=None, stylesheet=None, as_tree=False, as_json=False, maxbounds=False, filters=None, pretty_print=False, location_data=None, map_data=None, target=None, **args):
xml = current.xml output = None args = Storage(args) xmlformat = (S3XMLFormat(stylesheet) if stylesheet else None) tree = self.export_tree(start=start, limit=limit, msince=msince, fields=fields, dereference=dereference, maxdepth=maxdepth, mcomponents=mcomponents, rcomponents=rcomponents, references=...
'Export the resource as element tree @param start: index of the first record to export @param limit: maximum number of records to export @param msince: minimum modification date of the records @param fields: data fields to include (default: all) @param references: foreign keys to include (default: all) @param dereferen...
def export_tree(self, start=0, limit=None, msince=None, fields=None, references=None, dereference=True, maxdepth=MAXDEPTH, mcomponents=None, rcomponents=None, filters=None, maxbounds=False, xmlformat=None, location_data=None, map_data=None, target=None):
xml = current.xml if xml.show_urls: base_url = current.response.s3.base_url else: base_url = None self.muntil = None self.results = 0 lazy = [] current.auth_user_represent = S3Represent(lookup='auth_user', fields=['email']) table = self.table if (xml.filter_mci and ('...
'Add a <resource> to the element tree @param record: the record @param rfields: list of reference fields to export @param dfields: list of data fields to export @param parent: the parent element @param base_url: the base URL of the resource @param reference_map: the reference map of the request @param export_map: the e...
def __export_resource(self, record, rfields=[], dfields=[], parent=None, base_url=None, reference_map=None, export_map=None, lazy=None, components=None, filters=None, msince=None, master=True, target=None, location_data=None, xmlformat=None):
pkey = self.table._id if base_url: record_url = ('%s/%s' % (base_url, record[pkey])) else: record_url = None xml = current.xml MTIME = xml.MTIME MCI = xml.MCI export = self._export_record (element, rmap) = self._export_record(record, rfields=rfields, dfields=dfields, pare...
'Exports a single record to the element tree. @param record: the record @param rfields: list of foreign key fields to export @param dfields: list of data fields to export @param parent: the parent element @param export_map: the export map of the current request @param url: URL of the record @param master: True if this ...
def _export_record(self, record, rfields=[], dfields=[], parent=None, export_map=None, lazy=None, url=None, master=True, location_data=None):
xml = current.xml tablename = self.tablename table = self.table auth_user_represent = Storage() if hasattr(current, 'auth_user_represent'): user_ids = ('created_by', 'modified_by', 'owned_by_user') for fn in user_ids: if hasattr(table, fn): f = ogetattr(ta...
'Get a list of aliases of components that shall be exported together with the master resource @param tablename: the tablename of the master resource @param aliases: the list of required components @returns: a list of component aliases'
@staticmethod def components_to_export(tablename, aliases):
s3db = current.s3db if (aliases is not None): names = (aliases if aliases else None) hooks = s3db.get_components(tablename, names=names) else: hooks = {} hierarchy_link = s3db.hierarchy_link(tablename) (filtered, unfiltered) = ({}, {}) for (alias, hook) in hooks.items(): ...
'Add the record to the export map, and update the reference map with the record\'s references @param record: the record @param rmap: the reference map of the record @param reference_map: the reference map of the request @param export_map: the export map of the request'
def __map_record(self, record, rmap, reference_map, export_map):
tablename = self.tablename record_id = record[self.table._id] if rmap: reference_map.extend(rmap) if (tablename in export_map): export_map[tablename].append(record_id) else: export_map[tablename] = [record_id] return
'XML Importer @param source: the data source, accepts source=xxx, source=[xxx, yyy, zzz] or source=[(resourcename1, xxx), (resourcename2, yyy)], where the xxx has to be either an ElementTree or a file-like object @param files: attached files (None to read in the HTTP request) @param id: ID (or list of IDs) of the recor...
def import_xml(self, source, files=None, id=None, format='xml', stylesheet=None, extra_data=None, ignore_errors=False, job_id=None, commit_job=True, delete_job=False, strategy=None, update_policy=None, conflict_policy=None, last_sync=None, onconflict=None, **args):
has_permission = current.auth.s3_has_permission authorised = (has_permission('create', self.table) and has_permission('update', self.table)) if (not authorised): raise IOError('Insufficient permissions') xml = current.xml tree = None self.job = None if (not job_id): args.u...
'Import data from an S3XML element tree. @param id: record ID or list of record IDs to update @param tree: the element tree @param ignore_errors: continue at errors (=skip invalid elements) @param job_id: restore a job from the job table (ID or UID) @param delete_job: delete the import job from the job table @param com...
def import_tree(self, id, tree, job_id=None, ignore_errors=False, delete_job=False, commit_job=True, strategy=None, update_policy=None, conflict_policy=None, last_sync=None, onconflict=None):
from s3import import S3ImportJob db = current.db xml = current.xml auth = current.auth tablename = self.tablename table = self.table if (job_id is not None): self.error = None self.error_tree = None try: import_job = S3ImportJob(table, job_id=job_id, strat...
'Export field options of this resource as element tree @param component: name of the component which the options are requested of, None for the primary table @param fields: list of names of fields for which the options are requested, None for all fields (which have options) @param as_json: convert the output into JSON ...
def export_options(self, component=None, fields=None, only_last=False, show_uids=False, hierarchy=False, as_json=False):
if (component is not None): c = self.components.get(component) if c: tree = c.export_options(fields=fields, only_last=only_last, show_uids=show_uids, hierarchy=hierarchy, as_json=as_json) return tree else: raise AttributeError else: if (as_json...
'Export a list of fields in the resource as element tree @param component: name of the component to lookup the fields (None for primary table) @param as_json: convert the output XML into JSON'
def export_fields(self, component=None, as_json=False):
if (component is not None): c = self.components.get(component, None) if c: tree = c.export_fields() return tree else: raise AttributeError else: xml = current.xml tree = xml.get_fields(self.prefix, self.name) if as_json: ...
'Get the structure of the resource @param options: include option lists in option fields @param references: include option lists even for reference fields @param stylesheet: the stylesheet to use for transformation @param as_json: convert into JSON after transformation'
def export_struct(self, meta=False, options=False, references=False, stylesheet=None, as_json=False, as_tree=False):
xml = current.xml root = etree.Element(xml.TAG.root) main = xml.get_struct(self.prefix, self.name, alias=self.alias, parent=root, meta=meta, options=options, references=references) for component in self.components.values(): prefix = component.prefix name = component.name xml.get_...
'Find the original record for a possible duplicate: - if the record contains a UUID, then only that UUID is used to match the record with an existing DB record - otherwise, if the record contains some values for unique fields, all of them must match the same existing DB record @param table: the table @param record: the...
@classmethod def original(cls, table, record, mandatory=None):
db = current.db xml = current.xml xml_decode = xml.xml_decode VALUE = xml.ATTRIBUTE['value'] UID = xml.UID ATTRIBUTES_TO_FIELDS = xml.ATTRIBUTES_TO_FIELDS pkeys = [f for f in table.fields if table[f].unique] pvalues = Storage() get = record.get if (type(record) is etree._Element)...
'Get a list of all readable fields in the resource table @param subset: list of fieldnames to limit the selection to'
def readable_fields(self, subset=None):
fkey = None table = self.table parent = self.parent linked = self.linked if (parent and (linked is None)): component = parent.components.get(self.alias, None) if component: fkey = component.fkey elif (linked is not None): component = linked if componen...
'Resolve a list of field selectors against this resource @param selectors: the field selectors @param skip_components: skip fields in components @param extra_fields: automatically add extra_fields of all virtual fields in this table @param show: default for S3ResourceField.show @return: tuple of (fields, joins, left, d...
def resolve_selectors(self, selectors, skip_components=False, extra_fields=True, show=True):
prefix = (lambda s: (('~.%s' % s) if ('.' not in s.split('$', 1)[0]) else s)) display_fields = set() add = display_fields.add for item in selectors: if (not item): continue elif (type(item) is tuple): item = item[(-1)] if isinstance(item, str): ...
'Wrapper for S3ResourceField, retained for backward compatibility'
def resolve_selector(self, selector):
return S3ResourceField(self, selector)
'Split the readable fields in the resource table into reference and non-reference fields. @param skip: list of field names to skip @param data: data fields to include (None for all) @param references: foreign key fields to include (None for all)'
def split_fields(self, skip=[], data=None, references=None):
rfields = self.rfields dfields = self.dfields if ((rfields is None) or (dfields is None)): if (self.tablename == 'gis_location'): if (('wkt' not in skip) and (current.auth.permission.format != 'cap')): skip.append('wkt') if (current.deployment_settings.get_gis...
'Update configuration settings for this resource @param settings: configuration settings for this resource as keyword arguments'
def configure(self, **settings):
current.s3db.configure(self.tablename, **settings)
'Get a configuration setting for the current resource @param key: the setting key @param default: the default value to return if the setting is not configured for this resource'
def get_config(self, key, default=None):
return current.s3db.get_config(self.tablename, key, default=default)
'Clear configuration settings for this resource @param keys: keys to remove (can be multiple) @note: no keys specified removes all settings for this resource'
def clear_config(self, *keys):
current.s3db.clear_config(self.tablename, *keys)
'Convert start+limit parameters into a limitby tuple - limit without start => start = 0 - start without limit => limit = ROWSPERPAGE - limit 0 (or less) => limit = 1 - start less than 0 => start = 0 @param start: index of the first record to select @param limit: maximum number of records to select'
def limitby(self, start=0, limit=0):
if (limit is None): return None if (start is None): start = 0 if (limit == 0): limit = current.response.s3.ROWSPERPAGE if (limit <= 0): limit = 1 if (start < 0): start = 0 return (start, (start + limit))
'Get a join for this component @param implicit: return a subquery with an implicit join rather than an explicit join @param reverse: get the reverse join (joining master to component) @return: a Query if implicit=True, otherwise a list of joins'
def _join(self, implicit=False, reverse=False):
if (self.parent is None): return None else: ltable = self.parent.table rtable = self.table pkey = self.pkey fkey = self.fkey DELETED = current.xml.DELETED if self.linked: return self.linked._join(implicit=implicit, reverse=reverse) elif self.linktable: lin...
'Get join for this component'
def get_join(self):
return self._join(implicit=True)
'Get a left join for this component'
def get_left_join(self):
return self._join()
'Helper method to find the link table entry ID for a pair of linked records. @param master_id: the ID of the master record @param component_id: the ID of the component record'
def link_id(self, master_id, component_id):
if ((self.parent is None) or (self.linked is None)): return None join = self.get_join() ltable = self.table mtable = self.parent.table ctable = self.linked.table query = ((join & (mtable._id == master_id)) & (ctable._id == component_id)) row = current.db(query).select(ltable._id, lim...
'Helper method to find the component record ID for a particular link of a particular master record @param link: the link (S3Resource) @param master_id: the ID of the master record @param link_id: the ID of the link table entry'
def component_id(self, master_id, link_id):
if ((self.parent is None) or (self.linked is None)): return None join = self.get_join() ltable = self.table mtable = self.parent.table ctable = self.linked.table query = (join & (ltable._id == link_id)) if (master_id is not None): query &= (mtable._id == master_id) row = ...
'Create a new link in a link table if it doesn\'t yet exist. This function is meant to also update links in "embed" actuation mode once this gets implemented, therefore the method name "update_link". @param master: the master record @param record: the new component record to be linked'
def update_link(self, master, record):
if ((self.parent is None) or (self.linked is None)): return None resource = self.linked pkey = resource.pkey lkey = resource.lkey rkey = resource.rkey fkey = resource.fkey if (pkey not in master): return None _lkey = master[pkey] if (fkey not in record): retur...
'Parse datatable search/sort vars into a tuple of query, orderby and left joins @param fields: list of field selectors representing the order of fields in the datatable (list_fields) @param get_vars: the datatable GET vars @return: tuple of (query, orderby, left joins)'
def datatable_filter(self, fields, get_vars):
db = current.db left_joins = S3Joins(self.tablename) sSearch = 'sSearch' iColumns = 'iColumns' iSortingCols = 'iSortingCols' parent = self.parent fkey = self.fkey if (self.linked is not None): skip = self.linked.tablename else: skip = None rfields = self.resolve_s...
'Get all values for the given S3ResourceFields (axes) which match the resource query, used in pivot tables to filter out additional values where dimensions can have multiple values per record @param axes: the axis fields as list/tuple of S3ResourceFields @return: a dict with values per axis, only containes those axes w...
def axisfilter(self, axes):
axisfilter = {} qdict = self.get_query().as_dict(flat=True) for rfield in axes: field = rfield.field if (field is None): continue left_joins = S3Joins(self.tablename) left_joins.extend(rfield.left) tablenames = left_joins.joins.keys() tablenames.ap...
'Helper method to ensure consistent prefixing of field selectors @param selector: the selector'
def prefix_selector(self, selector):
head = selector.split('$', 1)[0] if ('.' in head): prefix = head.split('.', 1)[0] if (prefix == self.alias): return selector.replace(('%s.' % prefix), '~.') else: return selector else: return ('~.%s' % selector)
'Get the list_fields for this resource @param key: alternative key for the table configuration @param id_column: - False to exclude the record ID - True to include it if it is configured - 0 to make it the first column regardless whether it is configured or not'
def list_fields(self, key='list_fields', id_column=0):
list_fields = self.get_config(key, None) if ((not list_fields) and (key != 'list_fields')): list_fields = self.get_config('list_fields', None) if (not list_fields): list_fields = [f.name for f in self.readable_fields()] id_field = pkey = self._id.name if (self.parent and (not self.li...
'Get implicit defaults for new component records @param master: the master record @param defaults: any explicit defaults @param data: any actual values for the new record @return: a dict of {fieldname: values} with the defaults'
def get_defaults(self, master, defaults=None, data=None):
values = {} parent = self.parent if (not parent): return values hook = current.s3db.get_component(parent.tablename, self.alias) filterby = hook.get('filterby') if filterby: for (k, v) in filterby.items(): if (not isinstance(v, (tuple, list))): values[k...
'Get the original Table object (without SQL Alias), this is required for SQL update (DAL doesn\'t detect the alias and uses the wrong tablename).'
@property def _table(self):
if (self.tablename != self._alias): return current.s3db[self.tablename] else: return self.table
'Constructor, recursively introspect the query dict and extract all relevant subqueries. @param qdict: the query dict (from Query.as_dict(flat=True)) @param tablenames: the names of the relevant tables'
def __init__(self, qdict, tablenames):
self.l = None self.r = None self.op = None self.tablename = None self.fieldname = None if (not qdict): return l = qdict['first'] if ('second' in qdict): r = qdict['second'] else: r = None op = qdict['op'] if op: op = op.upper().strip('_') i...
'Reconstruct the query from this filter'
def query(self):
op = self.op if (op is None): return None if (self.tablename and self.fieldname): l = current.s3db[self.tablename][self.fieldname] elif self.l: l = self.l.query() else: l = None r = self.r if (op in ('AND', 'OR', 'NOT')): r = (r.query() if r else True)...
'Helper method to filter list:type axis values @param rfield: the axis field @return: pair of value lists [include], [exclude]'
def values(self, rfield):
op = self.op tablename = self.tablename fieldname = self.fieldname if ((tablename == rfield.tname) and (fieldname == rfield.fname)): value = self.r if isinstance(value, (list, tuple)): value = [s3_unicode(v) for v in value] if (not value): value = ...
'Constructor @param resource: the S3Resource @param id: the record ID (or list of record IDs) @param uid: the record UID (or list of record UIDs) @param filter: a filter query (S3ResourceQuery or Query) @param vars: the dict of GET vars (URL filters) @param extra_filters: extra filters (to be applied on pre-filtered su...
def __init__(self, resource, id=None, uid=None, filter=None, vars=None, extra_filters=None, filter_component=None):
self.resource = resource self.queries = [] self.filters = [] self.cqueries = {} self.cfilters = {} self._extra_filter_methods = None if extra_filters: self.set_extra_filters(extra_filters) else: self.efilters = [] self.query = None self.rfltr = None self.vfltr...
'Getter for extra filter methods, lazy property so methods are only imported/initialized when needed @todo: document the expected signature of filter methods @return: dict {name: callable} of known named filter methods'
@property def extra_filter_methods(self):
methods = self._extra_filter_methods if (methods is None): methods = {} self._extra_filter_methods = methods return methods
'Extend this filter @param query: a Query or S3ResourceQuery object @param component: alias of the component the filter shall be added to (None for master) @param master: False to filter only component'
def add_filter(self, query, component=None, master=True):
alias = None if (not master): if (not component): return if (component != self.resource.alias): alias = component if isinstance(query, S3ResourceQuery): self.transformed = None filters = self.filters cfilters = self.cfilters self.distin...
'Add an extra filter @param method: a name of a known filter method, or a callable filter method @param expression: the filter expression (string)'
def add_extra_filter(self, method, expression):
efilters = self.efilters efilters.append((method, expression)) return efilters