desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Probe whether the value pair matches the query @param l: the left value @param r: the right value'
def _probe(self, op, l, r):
result = False convert = S3TypeConverter.convert if (op == self.TYPEOF): if isinstance(l, (list, tuple, set)): op = self.ANYOF elif isinstance(r, (list, tuple, set)): op = self.BELONGS else: op = self.EQ if (op == self.CONTAINS): r = co...
'Probe whether a contains b'
@staticmethod def _probe_contains(a, b):
if (a is None): return False try: if isinstance(a, basestring): return (str(b) in a) elif isinstance(a, (list, tuple, set)): if isinstance(b, (list, tuple, set)): convert = S3TypeConverter.convert found = True for _b...
'Represent this query as a human-readable string. @param resource: the resource to resolve the query against'
def represent(self, resource):
op = self.op l = self.left r = self.right if (op == self.AND): l = (l.represent(resource) if isinstance(l, S3ResourceQuery) else str(l)) r = (r.represent(resource) if isinstance(r, S3ResourceQuery) else str(r)) return ('(%s and %s)' % (l, r)) elif (op == self.OR): ...
'Serialize this query as URL query @return: a Storage of URL variables'
def serialize_url(self, resource=None):
op = self.op l = self.left r = self.right url_query = Storage() def _serialize(n, o, v, invert): try: quote = (lambda s: (s if (',' not in s) else ('"%s"' % s))) if isinstance(v, list): v = ','.join([quote(S3TypeConverter.convert(str, val)) for val in ...
'Helper method to URL-serialize an OR-subtree in a query in alternative field selector syntax if they all use the same operator and value (this is needed to URL-serialize an S3SearchSimpleWidget query).'
def _or(self):
op = self.op l = self.left r = self.right if (op == self.AND): return None elif (op == self.NOT): (lname, lop, lval, linv) = l._or() return (lname, lop, lval, (not linv)) elif (op == self.OR): lvars = l._or() rvars = r._or() if ((lvars is None) or ...
'Construct a Storage of S3ResourceQuery from a Storage of get_vars @param resource: the S3Resource @param vars: the get_vars @return: Storage of S3ResourceQuery like {alias: query}, where alias is the alias of the component the query concerns'
@classmethod def parse(cls, resource, vars):
query = Storage() if (resource is None): return query if (not vars): return query subquery = cls._subquery allof = (lambda l, r: (l if (r is None) else (r if (l is None) else (r & l)))) for (key, value) in vars.iteritems(): if (not key): continue elif ...
'Parse a URL query into get_vars @param query: the URL query string @return: the get_vars (Storage)'
@staticmethod def parse_url(url):
if (not url): return Storage() elif ('?' in url): query = url.split('?', 1)[1] elif ('=' in url): query = url else: return Storage() import cgi dget = cgi.parse_qsl(query, keep_blank_values=1) get_vars = Storage() for (key, value) in dget: if (key ...
'Parse a URL expression @param key: the key for the URL variable @return: tuple (selectors, operator, invert)'
@staticmethod def parse_expression(key):
if (key[(-1)] == '!'): invert = True else: invert = False fs = key.rstrip('!') op = None if ('__' in fs): (fs, op) = fs.split('__', 1) op = op.strip('_') if (not op): op = 'eq' if ('|' in fs): selectors = [s for s in fs.split('|') if s] els...
'Parse a URL query value @param value: the value @return: the parsed value'
@staticmethod def parse_value(value):
uquote = (lambda w: w.replace('\\"', '\\"\\').strip('"').replace('\\"\\', '"')) NONE = ('NONE', 'None') if (type(value) is not list): value = [value] vlist = [] for item in value: w = '' quote = False ignore_quote = False for c in s3_unicode(item): ...
'Construct a sub-query from URL selectors, operator and value @param selectors: the selector(s) @param op: the operator @param invert: invert the query @param value: the value'
@classmethod def _subquery(cls, selectors, op, invert, value):
v = cls.parse_value(value) like = (lambda s: s3_unicode(s).lower().replace('%', '\\%').replace('_', '\\_').replace('?', '_').replace('*', '%').encode('utf-8')) q = None escaped = False for fs in selectors: if (op == S3ResourceQuery.LIKE): f = S3FieldSelector(fs).lower() ...
'Query constructor @param l: the left operand @param r: the right operand (string)'
@classmethod def like(cls, l, r):
string = cls.translate(r) if string: return l.lower().regexp(('^%s$' % string)) else: return l.like(r)
'Helper method to translate the search string into a regular expression @param string: the search string'
@classmethod def translate(cls, string):
if (not string): return None match = False output = [] append = output.append GROUPS = cls.GROUPS ESCAPE = cls.ESCAPE escaped = False for character in s3_unicode(string).lower(): result = None if (not escaped): if (character == '\\'): e...
'Constructor'
def __init__(self):
self.parser = None self.ParseResults = None self.ParseException = None self._parser()
'Import PyParsing and define the syntax for filter expressions'
def _parser(self):
try: import pyparsing as pp except ImportError: current.log.error('Advanced filter syntax requires pyparsing, $filter ignored') return False context = (lambda s, l, t: t[0].replace('[', '(').replace(']', ')')) selector = pp.Word((pp.alphas + '[]~'), (pp.alphanum...
'Parse a string expression and convert it into a dict of filters (S3ResourceQueries). @parameter expression: the filter expression as string @return: a dict of {component_alias: filter_query}'
def parse(self, expression):
query = {} parser = self.parser if ((not expression) or (parser is None)): return query try: parsed = parser.parseString(expression) except self.ParseException: current.log.error(("Invalid URL Filter Expression: '%s'" % expression)) else: if parsed: ...
'Convert a parsed filter expression into a dict of filters (S3ResourceQueries) @param expression: the parsed filter expression (ParseResults) @returns: a dict of {component_alias: filter_query}'
def convert_expression(self, expression):
ParseResults = self.ParseResults convert = self.convert_expression if isinstance(expression, ParseResults): (first, op, second) = ([None, None, None] + list(expression))[(-3):] if isinstance(first, ParseResults): first = convert(first) if isinstance(second, ParseResults):...
'Conjunction of two query {component_alias: filter_query} (AND) @param first: the first dict @param second: the second dict @return: the combined dict'
def _and(self, first, second):
if (not first): return second if (not second): return first result = dict(first) for (alias, subquery) in second.items(): if (alias not in result): result[alias] = subquery else: result[alias] &= subquery return result
'Disjunction of two query dicts {component_alias: filter_query} (OR) @param first: the first query dict @param second: the second query dict @return: the combined dict'
def _or(self, first, second):
if (not first): return second if (not second): return first if (len(first) > 1): first = {None: reduce(combine, first.values())} if (len(second) > 1): second = {None: reduce(combine, second.values())} falias = first.keys()[0] salias = second.keys()[0] alias = ...
'Negation of a query dict @param query: the query dict {component_alias: filter_query}'
def _not(self, query):
if (query is None): return None if (len(query) == 1): (alias, sub) = query.items()[0] if ((sub.op == S3ResourceQuery.OR) and (alias is None)): l = sub.left r = sub.right lalias = self._alias(sub.left.left) ralias = self._alias(sub.right.lef...
'Create an S3ResourceQuery @param op: the operator @param first: the first operand (=S3FieldSelector) @param second: the second operand (=value)'
def _query(self, op, first, second):
if (not isinstance(first, S3FieldSelector)): return {} selector = first alias = self._alias(selector) value = S3URLQuery.parse_value(second.strip()) if (op == S3ResourceQuery.LIKE): selector.lower() if isinstance(value, basestring): value = value.replace('*', '%')...
'Get the component alias from an S3FieldSelector (DRY Helper) @param selector: the S3FieldSelector @return: the alias as string or None for the master resource'
@staticmethod def _alias(selector):
alias = None if (selector and isinstance(selector, S3FieldSelector)): prefix = selector.name.split('$', 1)[0] if ('.' in prefix): alias = prefix.split('.', 1)[0] if (alias in ('~', '')): alias = None return alias
'Scheduler entry point, creates notification tasks for all active subscriptions which (may) have updates.'
@classmethod def check_subscriptions(cls):
_debug = current.log.debug now = datetime.datetime.utcnow() _debug(('S3Notifications.check_subscriptions(now=%s)' % now)) subscriptions = cls._subscriptions(now) if subscriptions: async = current.s3task.async for row in subscriptions: row.update_record(locked=True) ...
'Asynchronous task to notify a subscriber about updates, runs a POST?format=msg request against the subscribed controller which extracts the data and renders and sends the notification message (see send()). @param resource_id: the pr_subscription_resource record ID'
@classmethod def notify(cls, resource_id):
_debug = current.log.debug _debug(('S3Notifications.notify(resource_id=%s)' % resource_id)) db = current.db s3db = current.s3db stable = s3db.pr_subscription rtable = db.pr_subscription_resource ftable = s3db.pr_filter join = stable.on((rtable.subscription_id == stable.id)) left = ft...
'Method to retrieve updates for a subscription, render the notification message and send it - responds to POST?format=msg requests to the respective resource. @param r: the S3Request @param resource: the S3Resource'
@classmethod def send(cls, r, resource):
_debug = current.log.debug _debug('S3Notifications.send()') json_message = current.xml.json_message source = r.body source.seek(0) data = source.read() subscription = json.loads(data) notify_on = subscription['notify_on'] methods = subscription['method'] if ((not notify_on) or (n...
'Helper method to find all subscriptions which need to be notified now. @param now: current datetime (UTC) @return: joined Rows pr_subscription/pr_subscription_resource, or None if no due subscriptions could be found @todo: take notify_on into account when checking'
@classmethod def _subscriptions(cls, now):
db = current.db s3db = current.s3db stable = s3db.pr_subscription rtable = db.pr_subscription_resource query = ((((rtable.next_check_time == None) | (rtable.next_check_time <= now)) & (rtable.locked != True)) & (rtable.deleted != True)) tname = rtable.resource mtime = rtable.last_check_time....
'Method to pre-render the contents for the message template @param resource: the S3Resource @param data: the data returned from S3Resource.select @param meta_data: the meta data for the notification @param format: the contents format ("text" or "html")'
@classmethod def _render(cls, resource, data, meta_data, format=None):
created_on_selector = resource.prefix_selector('created_on') created_on_colname = None notify_on = meta_data['notify_on'] last_check_time = meta_data['last_check_time'] rows = data['rows'] rfields = data['rfields'] output = {} (new, upd) = ([], []) if (format == 'html'): coln...
'Constructor @param native_json: return the JSON string rather than a Python object (e.g. when the field is "string" type rather than "json") @param error_message: the error message'
def __init__(self, native_json=False, error_message='Invalid JSON'):
self.native_json = native_json self.error_message = error_message
'Validator, validates a string and converts it into db format'
def __call__(self, value):
error = (lambda v, e: (v, ('%s: %s' % (current.T(self.error_message), e)))) if current.response.s3.bulk: import ast try: value_ = json.dumps(ast.literal_eval(value), separators=SEPARATORS) except (JSONERRORS + (SyntaxError,)) as e: return error(value, e) ...
'Formatter, converts the db format into a string'
def formatter(self, value):
if ((value is None) or (self.native_json and isinstance(value, basestring))): return value else: return json.dumps(value, separators=SEPARATORS)
'Change the format of the number depending on the language Based on https://code.djangoproject.com/browser/django/trunk/django/utils/numberformat.py'
@staticmethod def represent(number):
if (number is None): return '' try: intnumber = int(number) except: intnumber = number settings = current.deployment_settings THOUSAND_SEPARATOR = settings.get_L10n_thousands_separator() NUMBER_GROUPING = settings.get_L10n_thousands_grouping() if (float(number) < 0): ...
'Change the format of the number depending on the language Based on https://code.djangoproject.com/browser/django/trunk/django/utils/numberformat.py @param number: the number @param precision: the number of decimal places to show @param fixed: show decimal places even if the decimal part is 0'
@staticmethod def represent(number, precision=None, fixed=False):
if (number is None): return '' DECIMAL_SEPARATOR = current.deployment_settings.get_L10n_decimal_separator() str_number = unicode(number) if ('.' in str_number): (int_part, dec_part) = str_number.split('.') if (precision is not None): dec_part = dec_part[:precision] ...
'Validator for foreign keys. @param dbset: a Set of records like db(query), or db itself @param field: the field in the referenced table @param label: lookup method for the label corresponding a value, alternatively a string template to be filled with values from the record @param filterby: a field in the referenced ta...
def __init__(self, dbset, field, label=None, filterby=None, filter_opts=None, not_filterby=None, not_filter_opts=None, realms=None, updateable=False, instance_types=None, error_message='invalid value!', orderby=None, groupby=None, left=None, multiple=False, zero='', sort=True, _and=None):
if hasattr(dbset, 'define_table'): self.dbset = dbset() else: self.dbset = dbset (ktable, kfield) = str(field).split('.') if (not label): label = ('%%(%s)s' % kfield) if isinstance(label, str): if regex1.match(str(label)): label = ('%%(%s)s' % str(label).s...
'This can be called from prep to apply a filter based on data in the record or the primary resource id.'
def set_filter(self, filterby=None, filter_opts=None, not_filterby=None, not_filter_opts=None):
if filterby: self.filterby = filterby if filter_opts: self.filter_opts = filter_opts if not_filterby: self.not_filterby = not_filterby if not_filter_opts: self.not_filter_opts = not_filter_opts
'Construct the query to lookup the options (separated from build_set so the query can be extracted and used in other lookups, e.g. filter options). @param table: the lookup table @param fields: fields (updatable list) @param dd: additional query options (updatable dict)'
def query(self, table, fields=None, dd=None):
method = ('update' if self.updateable else 'read') (query, left) = self.accessible_query(method, table, instance_types=self.instance_types) if ('deleted' in table): query &= (table['deleted'] != True) if self.realms: auth = current.auth if (auth.is_logged_in() and (auth.get_syste...
'Returns an accessible query (and left joins, if necessary) for records in table the user is permitted to access with method @param method: the method (e.g. "read" or "update") @param table: the table @param instance_types: list of instance tablenames, if table is a super-entity (required in this case!) @return: tuple ...
@classmethod def accessible_query(cls, method, table, instance_types=None):
DEFAULT = (table._id > 0) left = None if ('instance_type' in table): if (not instance_types): return (DEFAULT, left) query = None auth = current.auth s3db = current.s3db for instance_type in instance_types: itable = s3db.table(instance_type) ...
'Read the request.vars & prepare for a record insert/update Note: This is also used by IS_SITE_SELECTOR()'
def _process_values(self):
post_vars = current.request.post_vars lat = post_vars.get('gis_location_lat', None) lon = post_vars.get('gis_location_lon', None) if lat: try: lat = float(lat) except ValueError: self.errors['lat'] = current.T('Latitude is Invalid!') if lon: try:...
'Constructor @param error_message: alternative error message @param allow_empty: allow the selector to be left empty @param first_name_only: put all name elements into first_name field None => activate if RTL otherwise don\'t @note: This validator can *not* be used together with IS_EMPTY_OR, because when a new person g...
def __init__(self, error_message=None, allow_empty=False, first_name_only=None, separate_name_fields=None):
self.error_message = error_message self.allow_empty = allow_empty self.first_name_only = first_name_only self.separate_name_fields = separate_name_fields self.mark_required = (not allow_empty)
'Constructor @param format: strptime/strftime format template string, for directives refer to your strptime implementation @param error_message: error message for invalid date/times @param offset_error: error message for invalid UTC offset @param utc_offset: offset to UTC in hours, defaults to the current session\'s UT...
def __init__(self, format=None, error_message=None, offset_error=None, utc_offset=None, calendar=None, minimum=None, maximum=None):
if (format is None): self.format = str(current.deployment_settings.get_L10n_datetime_format()) else: self.format = str(format) if isinstance(calendar, basestring): from s3datetime import S3Calendar calendar = S3Calendar(calendar) elif (calendar == None): calendar ...
'Compute the delta in seconds for the current UTC offset @param utc_offset: the offset (override defaults) @return: the offset in seconds'
def delta(self, utc_offset=None):
if (utc_offset is None): utc_offset = self.utc_offset if (utc_offset is None): utc_offset = current.session.s3.utc_offset return S3DateTime.get_offset_value(utc_offset)
'Validate a value, and convert it into a timezone-naive datetime.datetime object as necessary @param value: the value to validate @return: tuple (value, error)'
def __call__(self, value):
if isinstance(value, basestring): val = value.strip() if ((len(val) > 5) and (val[(-5)] in ('+', '-')) and val[(-4):].isdigit()): (dtstr, utc_offset) = (val[0:(-5)].strip(), val[(-5):]) else: (dtstr, utc_offset) = (val, None) dt = self.calendar.parse_datetime(...
'Format a datetime as string. @param value: the value'
def formatter(self, value):
if (not value): return current.messages['NONE'] offset = self.delta() if offset: value += datetime.timedelta(seconds=offset) result = self.calendar.format_datetime(value, dtfmt=self.format, local=True) return result
'Constructor @param format: strptime/strftime format template string, for directives refer to your strptime implementation @param error_message: error message for invalid date/times @param offset_error: error message for invalid UTC offset @param calendar: calendar to use for string evaluation, defaults to current.cale...
def __init__(self, format=None, error_message=None, offset_error=None, calendar=None, utc_offset=None, minimum=None, maximum=None):
if (format is None): self.format = str(current.deployment_settings.get_L10n_date_format()) else: self.format = str(format) if isinstance(calendar, basestring): from s3datetime import S3Calendar calendar = S3Calendar(calendar) elif (calendar == None): calendar = cu...
'Validate a value, and convert it into a datetime.date object as necessary @param value: the value to validate @return: tuple (value, error)'
def __call__(self, value):
is_datetime = False if isinstance(value, basestring): dt = self.calendar.parse_date(value.strip(), dtfmt=self.format, local=True) if (dt is None): return (value, self.error_message) elif isinstance(value, datetime.datetime): dt = value is_datetime = True elif ...
'Format a date as string. @param value: the value'
def formatter(self, value):
if (not value): return current.messages['NONE'] offset = self.delta() if offset: delta = datetime.timedelta(seconds=offset) if (not isinstance(value, datetime.datetime)): combine = datetime.datetime.combine bp = (combine(value, datetime.time(8, 0, 0)) - delta)...
'Validation @param value: the value to validate'
def __call__(self, value):
if (not isinstance(value, (list, tuple))): value = [value] acl = 0 for v in value: try: flag = int(v) except (ValueError, TypeError): flag = 0 else: acl |= flag return (acl, None)
'Constructor @param international: enforce E.123 international notation, no effect if turned off globally in deployment settings @param error_message: alternative error message'
def __init__(self, international=False, error_message=None):
self.international = international self.error_message = error_message
'Validation of a value @param value: the value @return: tuple (value, error), where error is None if value is valid. With international=True, the value returned is converted into E.123 international notation.'
def __call__(self, value):
if isinstance(value, basestring): value = value.strip() if (value and (value[0] == unichr(8206))): value = value[1:] number = s3_str(value) (number, error) = s3_single_phone_requires(number) else: error = True if (not error): if (self.international...
'Constructor @param error_message: alternative error message'
def __init__(self, error_message=None):
self.error_message = error_message
'Validation of a value @param value: the value @return: tuple (value, error), where error is None if value is valid.'
def __call__(self, value):
value = value.strip() if (value[0] == unichr(8206)): value = value[1:] number = s3_str(value) (number, error) = s3_phone_requires(number) if (not error): return (number, None) error_message = self.error_message if (not error_message): error_message = current.T('Enter ...
'Constructor @param error_message: the error message for invalid values'
def __init__(self, error_message='Invalid field name'):
self.error_message = error_message
'Validation of a value @param value: the value @return: tuple (value, error)'
def __call__(self, value):
if value: name = str(value).lower().strip() from s3fields import s3_all_meta_field_names if ((name != 'id') and (name not in s3_all_meta_field_names()) and self.PATTERN.match(name)): return (name, None) return (value, self.error_message)
'Constructor @param error_message: the error message for invalid values'
def __init__(self, error_message='Unsupported field type'):
self.error_message = error_message
'Validation of a value @param value: the value @return: tuple (value, error)'
def __call__(self, value):
if value: field_type = str(value).lower().strip() items = field_type.split(' ') base_type = items[0] if (base_type == 'reference'): if (len(items) > 1): ktablename = items[1].split('.')[0] ktable = current.s3db.table(ktablename, db_only=...
'Constructor @param error_message: alternative error message @param multiple: allow selection of multiple options @param select: dict of options for the selector, defaults to settings.L10n.languages, set explicitly to None to allow all languages @param sort: sort options in selector @param translate: translate the lang...
def __init__(self, error_message='Invalid language code', multiple=False, select=DEFAULT, sort=False, translate=False, zero=''):
super(IS_ISO639_2_LANGUAGE_CODE, self).__init__(self.language_codes(), error_message=error_message, multiple=multiple, zero=zero, sort=sort) if (select is DEFAULT): self._select = current.deployment_settings.get_L10n_languages() else: self._select = select self.translate = translate
'Get the options for the selector. This could be only a subset of all valid options (self._select), therefore overriding superclass function here.'
def options(self, zero=True):
language_codes = self.language_codes() if self._select: language_codes_dict = dict(language_codes) items = [(k, v) for (k, v) in self._select.items() if (k in language_codes_dict)] elif self.translate: T = current.T items = [(k, T(v)) for (k, v) in self.language_codes()] ...
'Represent a language code by language name, uses the representation from deployment_settings if available rather than translation into current UI language. @param code: the language code'
@classmethod def represent(cls, code):
l10n_languages = current.deployment_settings.get_L10n_languages() if (code in l10n_languages): name = l10n_languages[code] else: name = cls.represent_local(code) return name
'Represent a language code by language name, translated into current UI language (preferrable for database fields). @param code: the language code'
@classmethod def represent_local(cls, code):
name = dict(cls.language_codes()).get(code) if (name is None): name = current.messages.UNKNOWN_OPT else: name = current.T(name) return name
'Returns a list of tuples of ISO639-1 alpha-2 language codes, can also be used to look up the language name Just the subset which are useful for Translations - 2 letter code preferred, 3-letter code where none exists, no \'families\' or Old'
@staticmethod def language_codes():
lang = [('aa', 'Afar'), ('ab', 'Abkhazian'), ('ace', 'Achinese'), ('ach', 'Acoli'), ('ada', 'Adangme'), ('ady', 'Adyghe; Adygei'), ('afh', 'Afrihili'), ('af', 'Afrikaans'), ('ain', 'Ainu'), ('ak', 'Akan'), ('akk', 'Akkadian'), ('sq', 'Albanian'), ('ale', 'Aleut'), ('alt', 'Southern Altai'), ('am', 'Amharic'),...
'Apply CRUD methods @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view Known means of communicating with this module: It expects a URL of the form: /prefix/name/import It will interpret the http requests as follows: GET will trigger the up...
def apply_method(self, r, **attr):
T = current.T messages = self.messages = Messages(T) messages.download_template = 'Download Template' messages.invalid_file_format = 'Invalid File Format' messages.unsupported_file_type = 'Unsupported file type of %s' messages.stylesheet_not_found = 'No Stylesheet %s ...
'This will display the upload form It will ask for a file to be uploaded or for a job to be selected. If a file is uploaded then it will guess at the file type and ask for the transform file to be used. The transform files will be in a dataTable with the module specific files shown first and after those all other known...
def upload(self, r, **attr):
request = self.request form = self._upload_form(r, **attr) output = self._create_upload_dataTable() if (request.representation == 'aadata'): return output output.update(form=form, title=self.uploadTitle) return output
'Generate an ImportJob from the submitted upload form'
def generate_job(self, r, **attr):
response = current.response s3 = response.s3 db = current.db table = self.upload_table output = None if self.ajax: sfilename = ofilename = r.post_vars['file'].filename upload_id = table.insert(controller=self.controller, function=self.function, filename=ofilename, file=sfilename,...
'@todo: docstring?'
def display_job(self, upload_id):
db = current.db request = self.request table = self.upload_table job_id = self.job_id if (job_id is None): query = (table.id == upload_id) db(query).update(status=2) current.session.warning = self.messages.no_records_to_import redirect(URL(r=request, f=self.function, ...
'@todo: docstring?'
def commit(self, source, transform):
session = current.session try: openFile = open(source, 'r') except: session.error = (self.messages.file_open_error % source) redirect(URL(r=self.request, f=self.function)) extension = source.rsplit('.', 1).pop() if (extension not in ('csv, xls', 'xlsx', 'xlsm')): f...
'@todo: docstring?'
def commit_items(self, upload_id, items):
self._commit_import_job(upload_id, items) result = self._update_upload_job(upload_id) if self.ajax: return result self._display_completed_job(result) redirect(URL(r=self.request, f=self.function, args=['import']))
'Delete an uploaded file and the corresponding import job @param upload_id: the upload ID'
def delete_job(self, upload_id):
db = current.db request = self.request resource = request.resource job_id = self.job_id if job_id: result = resource.import_xml(None, id=None, tree=None, job_id=job_id, delete_job=True) count = db((self.upload_table.id == upload_id)).delete() db.commit() result = count if (re...
'Create and process the upload form, including csv_extra_fields'
def _upload_form(self, r, **attr):
EXTRA_FIELDS = 'csv_extra_fields' TEMPLATE = 'csv_template' REPLACE_OPTION = 'replace_option' response = current.response s3 = response.s3 request = self.request table = self.upload_table formstyle = s3.crud.formstyle response.view = self._view(request, 'list_filter.html') if (RE...
'List of previous Import jobs'
def _create_upload_dataTable(self):
db = current.db request = self.request controller = self.controller function = self.function s3 = current.response.s3 table = self.upload_table s3.filter = ((table.controller == controller) & (table.function == function)) self._use_upload_table() output = dict() self._use_control...
'@todo: docstring?'
def _create_import_item_dataTable(self, upload_id, job_id):
s3 = current.response.s3 represent = {'s3_import_item.element': self._item_element_represent} self._use_import_item_table(job_id) table = self.table query = ((table.job_id == job_id) & (table.tablename == self.controller_tablename)) rows = current.db(query).select(table.id, table.error) sele...
'This will take a s3_import_upload record and generate the importJob @param uploadFilename: The name of the uploaded file @todo: complete parameter descriptions'
def _generate_import_job(self, upload_id, openFile, fileFormat, stylesheet=None, commit_job=False):
if (fileFormat in ('csv', 'comma-separated-values')): fmt = 'csv' src = openFile elif (fileFormat in ('xls', 'xlsx', 'xlsm')): fmt = 'xls' src = openFile else: msg = (self.messages.unsupported_file_type % fileFormat) self.error = msg current.log.debug(...
'Get the stylesheet for transformation of the import @param file_format: the import source file format'
def _get_stylesheet(self, file_format='csv'):
if (file_format == 'csv'): xslt_path = os.path.join(self.xslt_path, 's3csv') else: xslt_path = os.path.join(self.xslt_path, file_format, 'import.xsl') return xslt_path if self.csv_stylesheet: if isinstance(self.csv_stylesheet, (tuple, list)): stylesheet = os.path....
'This will save all of the selected import items @todo: parameter descriptions?'
def _commit_import_job(self, upload_id, items):
db = current.db resource = self.request.resource self.importDetails = dict() table = self.upload_table row = db((table.id == upload_id)).select(table.job_id, table.replace_option, limitby=(0, 1)).first() if (row is None): return False else: job_id = row.job_id current...
'This will store the details from an importJob @todo: parameter descriptions?'
def _store_import_details(self, job_id, key):
itable = S3ImportJob.define_item_table() query = ((itable.job_id == job_id) & (itable.tablename == self.controller_tablename)) rows = current.db(query).select(itable.data, itable.error) items = [dict(data=row.data, error=row.error) for row in rows] self.importDetails[key] = items
'This will record the results from the import, and change the status of the upload job @todo: parameter descriptions? @todo: report errors in referenced records, too'
def _update_upload_job(self, upload_id):
resource = self.request.resource db = current.db totalPreDelete = len(self.importDetails['preDelete']) totalPreImport = len(self.importDetails['preImportTree']) totalIgnored = (totalPreDelete - totalPreImport) if (resource.error_tree is None): totalErrors = 0 else: totalError...
'Generate a summary flash message for a completed import job @param totals: the job totals as tuple (total imported, total errors, total ignored) @param timestmp: the timestamp of the completion'
def _display_completed_job(self, totals, timestmp=None):
messages = self.messages msg = ('%s - %s - %s' % (messages.commit_total_records_imported, messages.commit_total_errors, messages.commit_total_records_ignored)) msg = (msg % totals) if (timestmp != None): current.session.flash = (messages.job_completed % (self.date_represent(timestmp)...
'Method to get the data for the dataTable This can be either a raw html representation or and ajax call update Additional data will be cached to limit calls back to the server @param list_fields: list of field names @param sort_by: list of sort by columns @param represent: a dict of field callback functions used to cha...
def _dataTable(self, list_fields, sort_by=[[1, 'asc']], represent={}, ajax_item_id=None, dt_bulk_select=[]):
from s3data import S3DataTable request = self.request resource = self.resource s3 = current.response.s3 if (s3.filter is not None): self.resource.add_filter(s3.filter) representation = request.representation totalrows = None if (representation == 'aadata'): (searchq, orde...
'Represent the element in an import item for dataTable display @param value: the string containing the element'
def _item_element_represent(self, id, value):
try: element = etree.fromstring(value) except: return DIV(value) db = current.db tablename = element.get('name') table = db[tablename] output = DIV() details = TABLE(_class=('importItem %s' % id)) (header, rows) = self._add_item_details(element.findall('data'), table) ...
'Add details of the item element @param data: the list of data elements in the item element @param table: the table for the data @param details: the existing details rows list (to append to)'
@staticmethod def _add_item_details(data, table, details=None, prefix=False):
tablename = table._tablename if (details is None): details = [] first = None firstString = None header = None for child in data: f = child.get('field', None) if (f not in table.fields): continue elif (f == 'wkt'): continue field = t...
'Try to decode string data into their original type @param field: the Field instance @param value: the stringified value @todo: replace this by ordinary decoder'
@staticmethod def _decode_data(field, value):
if ((field.type == 'string') or (field.type == 'string') or (field.type == 'password') or (field.type == 'upload') or (field.type == 'text')): return value elif ((field.type == 'integer') or (field.type == 'id')): return int(value) elif ((field.type == 'double') or (field.type == 'decimal'))...
'Represent a datetime object as string @param date_obj: the datetime object @todo: replace by S3DateTime method?'
@staticmethod def date_represent(date_obj):
return date_obj.strftime('%d %B %Y, %I:%M%p')
'Get the list of IDs for the selected items from the "mode" and "selected" request variables @param upload_id: the upload_id @param vars: the request variables'
def _process_item_list(self, upload_id, vars):
items = None if ('mode' in vars): mode = vars['mode'] if ('selected' in vars): selected = vars['selected'] else: selected = [] if (mode == 'Inclusive'): items = selected elif (mode == 'Exclusive'): all_items = self._get_all_...
'Get a list of the record IDs of all import items for the the given upload ID @param upload_id: the upload ID @param as_string: represent each ID as string'
def _get_all_items(self, upload_id, as_string=False):
item_table = S3ImportJob.define_item_table() upload_table = self.upload_table query = (((upload_table.id == upload_id) & (item_table.job_id == upload_table.job_id)) & (item_table.tablename == self.controller_tablename)) rows = current.db(query).select(item_table.id) if as_string: items = [st...
'Set the resource and the table to being s3_import_upload'
def _use_upload_table(self):
self.tablename = self.upload_tablename if (self.upload_resource is None): self.upload_resource = current.s3db.resource(self.tablename) self.resource = self.upload_resource self.table = self.upload_table
'Set the resource and the table to be the imported resource'
def _use_controller_table(self):
self.resource = self.controller_resource self.table = self.controller_table self.tablename = self.controller_tablename
'Set the resource and the table to being s3_import_item'
def _use_import_item_table(self, job_id):
self.table = S3ImportJob.define_item_table() self.tablename = S3ImportJob.ITEM_TABLE_NAME if (self.item_resource == None): self.item_resource = current.s3db.resource(self.tablename) self.resource = self.item_resource
'Configures the upload table'
def __define_table(self):
T = current.T request = current.request self.upload_tablename = self.UPLOAD_TABLE_NAME import_upload_status = {1: T('Pending'), 2: T('In error'), 3: T('Completed')} now = request.utcnow table = self.define_upload_table() table.file.upload_folder = os.path.join(request.folder, 'uploads') ...
'Defines the upload table'
@classmethod def define_upload_table(cls):
db = current.db UPLOAD_TABLE_NAME = cls.UPLOAD_TABLE_NAME if (UPLOAD_TABLE_NAME not in db): db.define_table(UPLOAD_TABLE_NAME, Field('controller', readable=False, writable=False), Field('function', readable=False, writable=False), Field('file', 'upload', length=current.MAX_FILENAME_LENGTH, uploadfol...
'Constructor @param job: the import job this item belongs to'
def __init__(self, job):
self.job = job self.lock = False self.error = None self.item_id = uuid.uuid4() self.id = None self.uid = None self.table = None self.tablename = None self.element = None self.data = None self.original = None self.components = [] self.references = [] self.load_comp...
'Helper method for debugging'
def __repr__(self):
_str = ('<S3ImportItem %s {item_id=%s uid=%s id=%s error=%s data=%s}>' % (self.table, self.item_id, self.uid, self.id, self.error, self.data)) return _str
'Read data from a <resource> element @param element: the element @param table: the DB table @param tree: the import tree @param files: uploaded files @return: True if successful, False if not (sets self.error)'
def parse(self, element, original=None, table=None, tree=None, files=None):
s3db = current.s3db xml = current.xml ERROR = xml.ATTRIBUTE['error'] self.element = element if (table is None): tablename = element.get(xml.ATTRIBUTE['name']) table = s3db.table(tablename) if (table is None): self.error = current.ERROR.BAD_RESOURCE ele...
'Detect whether this is an update or a new record'
def deduplicate(self):
table = self.table if ((table is None) or self.id): return METHOD = self.METHOD CREATE = METHOD['CREATE'] UPDATE = METHOD['UPDATE'] DELETE = METHOD['DELETE'] MERGE = METHOD['MERGE'] xml = current.xml UID = xml.UID data = self.data if (self.job.second_pass and (UID in ...
'Authorize the import of this item, sets self.permitted'
def authorize(self):
if (not self.table): return False auth = current.auth tablename = self.tablename if ((not auth.override) and (tablename.split('_', 1)[0] in auth.PROTECTED)): return False METHOD = self.METHOD if (self.data.deleted is True): if self.data.deleted_rb: self.method...
'Validate this item (=record onvalidation), sets self.accepted'
def validate(self):
data = self.data if (self.accepted is not None): return self.accepted if ((data is None) or (not self.table)): self.accepted = False return False xml = current.xml ERROR = xml.ATTRIBUTE['error'] METHOD = self.METHOD DELETE = METHOD.DELETE MERGE = METHOD.MERGE ...
'Commit this item to the database @param ignore_errors: skip invalid components (still reports errors)'
def commit(self, ignore_errors=False):
if self.committed: return True if ((self.parent is not None) and self.parent.skip): return True db = current.db s3db = current.s3db xml = current.xml ATTRIBUTE = xml.ATTRIBUTE METHOD = self.METHOD CREATE = METHOD.CREATE UPDATE = METHOD.UPDATE DELETE = METHOD.DELET...
'Applies dynamic defaults from any keys in data that start with an underscore, used only for new records and only if the respective field is not populated yet. @param data: the data dict'
def _dynamic_defaults(self, data):
for (k, v) in data.items(): if (k[0] == '_'): fn = k[1:] if ((fn in self.table.fields) and (fn not in data)): data[fn] = v
'Resolve the references of this item (=look up all foreign keys from other items of the same job). If a foreign key is not yet available, it will be scheduled for later update.'
def _resolve_references(self):
table = self.table if (not table): return db = current.db items = self.job.items for reference in self.references: entry = reference.entry if (not entry): continue field = reference.field if isinstance(field, (list, tuple)): (pkey, fkey...
'Helper method to update a foreign key in an already written record. Will be called by the referenced item after (and only if) it has been committed. This is only needed if the reference could not be resolved before commit due to circular references. @param field: the field name of the foreign key @param value: the val...
def _update_reference(self, field, value):
MTIME = current.xml.MTIME table = self.table record_id = self.id if ((not value) or (not table) or (not record_id) or (not self.permitted)): return if (MTIME in table.fields): modified_on = table[MTIME] modified_on_update = modified_on.update modified_on.update = None...
'Store this item in the DB'
def store(self, item_table=None):
if (item_table is None): return None db = current.db row = db((item_table.item_id == self.item_id)).select(item_table.id, limitby=(0, 1)).first() if row: record_id = row.id else: record_id = None record = Storage(job_id=self.job.job_id, item_id=self.item_id, tablename=sel...
'Restore an item from a item table row. This does not restore the references (since this can not be done before all items are restored), must call job.restore_references() to do that @param row: the item table row'
def restore(self, row):
xml = current.xml self.item_id = row.item_id self.accepted = None self.permitted = False self.committed = False tablename = row.tablename self.id = None self.uid = row.record_uid if (row.data is not None): self.data = cPickle.loads(row.data) else: self.data = Stor...
'Constructor @param tree: the element tree to import @param files: files attached to the import (for upload fields) @param job_id: restore job from database (record ID or job_id) @param strategy: the import strategy @param update_policy: the update policy @param conflict_policy: the conflict resolution policy @param la...
def __init__(self, table, tree=None, files=None, job_id=None, strategy=None, update_policy=None, conflict_policy=None, last_sync=None, onconflict=None):
self.error = None self.error_tree = etree.Element(current.xml.TAG.root) self.table = table self.tree = tree self.files = files self.directory = Storage() self.mandatory_fields = Storage() self.elements = Storage() self.items = Storage() self.references = [] self.job_table = N...
'Parse and validate an XML element and add it as new item to the job. @param element: the element @param original: the original DB record (if already available, will otherwise be looked-up by this function) @param components: a dictionary of components (as in S3Resource) to include in the job (defaults to all defined c...
def add_item(self, element=None, original=None, components=None, parent=None, joinby=None):
if (element in self.elements): return self.elements[element] item = S3ImportItem(self) item_id = item.item_id self.items[item_id] = item if (element is not None): self.elements[element] = item_id if (not item.parse(element, original=original, files=self.files)): self.erro...