def process_url_params(params, columns): """ Converts a dictionary of parameters from the user to sql filters. If a parameter is of the form <field name>-<suffix>, where suffix is defined in `sql_directives`, the corresponding function is used to produce a filter. """ # support passing `format` instead of `$format` so we don't break people's # existing URLs. Let's remove this once we can. format_ = params.get('$format', params.get('format', Format.UNZIPPED_CSV)) keyword_filters = {} sql_filters = [] for key, value in params.items(): if key in ('$format', 'format'): continue for suffix, fn in sql_directives: if key.endswith(suffix): field = key[:-len(suffix)] if field not in columns: raise UserQueryError(_('No field named {}').format(field)) sql_filters.append(fn(columns[field], value)) break else: if key in columns: keyword_filters[key] = value else: raise UserQueryError( _('Invalid filter parameter: {}').format(key)) return ExportParameters(format_, keyword_filters, sql_filters)
def _range_filter(column, value): try: start, end = value.split('..') except ValueError: raise UserQueryError(_('Ranges must have the format "start..end"')) return column.between(start, end)
def _last_n_days(column, value): if not isinstance(column.type, (types.Date, types.DateTime)): raise UserQueryError(_("You can only use 'lastndays' on date columns")) end = datetime.date.today() start = end - datetime.timedelta(days=int(value)) return column.between(start, end)