desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Constructor'
| def __init__(self):
| self.widgets = {}
|
'Add XML for a widget to this channel
@param widget: the widget XML (e.g. DIV instance)
@param position: the position of the widget in the channel,
if there are multiple widgets in the channel'
| def add_widget(self, widget, position=None):
| widgets = self.widgets
if (position not in widgets):
widgets[position] = [widget]
else:
widgets[position].append(widget)
|
'Iterate over the widgets in this channel, in order of their
positions; used in layouts to build the channel contents.
@note: Widgets without explicit position (=None), or multiple
widgets at the same position, will be returned in the
order in which they have been added to the channel.'
| def __iter__(self):
| widgets = self.widgets
positions = sorted((p for p in widgets if (p is not None)))
if (None in widgets):
positions.append(None)
for position in positions:
widget_list = widgets[position]
for widget in widget_list:
(yield widget)
|
'Number of widgets in this channel, useful for sizing of
container elements in layouts:
- number_of_widgets = len(channel)'
| def __len__(self):
| total = sum((len(widgets) for widgets in self.widgets.values()))
return total
|
'Build the layout with the contents added by agents
- to be implemented in subclasses
@param context: the current S3DashboardContext
@return: the dashboard contents, usually a TAG instance,
alternatively a dict for the view (for custom
views)
@note: can override current.response.view to use a
specific view template (de... | def build(self, context):
| return ''
|
'Add contents to layout,
- can be overwritten in subclasses (e.g. to dynamically
create channels)
@param contents: the contents to insert
@param channel: the channel where to insert the contents,
using the default channel if None
@param position: the position within the channel (numeric),
append to channel if None'
| def add_widget(self, widget, channel=DEFAULT, position=None):
| if (channel is DEFAULT):
channel = self.DEFAULT_CHANNEL
channel_ = self.channels.get(channel)
if (channel_ is not None):
channel_.add_widget(widget, position=position)
|
'Build a single channel, usually called by build()
@param key: the channel key
@param attr: HTML attributes for the channel
@return: the XML for the channel, usually a DIV instance'
| def build_channel(self, key, **attr):
| widgets = default = XML(' ')
channel = self.channels.get(key)
if (channel is not None):
widgets = [w for w in channel]
if (not widgets):
widgets = default
return DIV(widgets, **attr)
|
'Constructor
@param config: the active S3DashboardConfig'
| def __init__(self, config):
| self.config = config
CHANNELS = self.CHANNELS
if CHANNELS:
self.channels = dict(((name, S3DashboardChannel()) for name in CHANNELS))
else:
self.channels = {}
|
'Build the layout with the contents added by agents
@param context: the current S3DashboardContext
@return: the dashboard contents (TAG)'
| def build(self, context):
| T = current.T
channel = self.build_channel
contents = TAG[''](DIV(channel('N', _class='small-12 columns db-box db-box-n'), _class='row'), DIV(channel('W', _class='small-3 columns db-box db-box-w'), channel('C', _class='small-6 columns db-box db-box-c'), channel('E', _class='small-... |
'Initializes the dashboard
@param config: the default configuration for this dashboard
@param layouts: custom layouts to override/extend the available
layouts, as dict {name: (label, class)}'
| def __init__(self, config, layouts=None):
| if (not isinstance(config, S3DashboardConfig)):
config = S3DashboardConfig(config)
self._config = config
self.context = S3DashboardContext(dashboard=self)
available_layouts = dict(self.layouts)
if layouts:
available_layouts.update(layouts)
self.available_layouts = available_layou... |
'Lazy property to load the current configuration from the database
@return: the S3DashboardConfig'
| @property
def config(self):
| config = self._config
if (not config.loaded):
config.load(self.context)
return config
|
'Lazy property to instantiate the dashboard agents
@return: a dict {agent_id: agent}'
| @property
def agents(self):
| agents = self._agents
if (agents is None):
config = self.config
context = self.context
config_id = config.config_id
available_widgets = config.available_widgets
next_id = config.next_id
agents = self._agents = {}
for (index, widget_config) in enumerate(con... |
'Dispatch requests - this method is called by the controller.
@param attr: keyword arguments from the controller
@keyword _id: the node ID for the dashboard (default: "dashboard")
@return: the output for the view'
| def __call__(self, **attr):
| context = self.context
agent_id = context.agent
http = context.http
command = context.command
(status, msg) = (None, None)
if (agent_id or command or (http != 'GET')):
request_version = context.get_vars.get('version')
if (not request_version):
context.error(400, curre... |
'Build the dashboard and all its contents
@param attr: keyword arguments from the controller
@return: the output dict for the view'
| def build(self, **attr):
| config = self.config
context = self.context
dashboard_id = attr.get('_id', 'dashboard')
hide = (' hide' if (not config.configurable) else '')
switch = SPAN(ICON('settings', _class=('db-config-on%s' % hide)), ICON('done', _class='db-config-off hide'), _class='db-config', data={'mode': 'off'})
... |
'Execute a dashboard global command
@param command: the command
@param context: the current S3DashboardContext
@todo: implement global commands'
| def do(self, command, context):
| output = None
error = (501, current.ERROR.NOT_IMPLEMENTED)
return (output, error)
|
'Get the active layout
@param config: the active dashboard configuration
@return: an instance of the active layout'
| def get_active_layout(self, config):
| layout = self.available_layouts.get(config.layout)
if (layout is None):
layout = S3DashboardBoxesLayout
elif (type(layout) is tuple):
layout = layout[(-1)]
return layout(config)
|
'Inject the JS to instantiate the client-side widget controller
@param dashboard_id: the dashboard DOM node ID
@param options: JSON-serializable dict with script options'
| @staticmethod
def inject_script(dashboard_id, options=None):
| s3 = current.response.s3
scripts = s3.scripts
appname = current.request.application
if s3.debug:
script = ('/%s/static/scripts/S3/s3.ui.dashboard.js' % appname)
if (script not in scripts):
scripts.append(script)
else:
script = ('/%s/static/scripts/S3/s3.ui.dashboa... |
'Initialize the agent
@param agent_id: the agent ID (string), a unique XML
identifier for the widget configuration
@param widget: the widget (S3DashboardWidget instance)
@param config: the widget configuration (dict)
@param version: the config version'
| def __init__(self, agent_id, widget=None, config=None, version=None):
| self.agent_id = agent_id
self.widget = widget
self.config = config
self.version = version
|
'Dispatch Ajax requests
@param dashboard: the calling S3Dashboard instance
@param context: the current S3DashboardContext
@return: tuple (output, error), where:
- "output" is the output of the command execution
- "error" is a tuple (http_status, message), or None'
| def __call__(self, dashboard, context):
| command = context.command
representation = context.representation
output = None
error = None
if command:
if (command == 'config'):
if (representation == 'popup'):
output = self.configure(dashboard, context)
else:
error = (415, current.E... |
'Execute a delegated widget method
@param command: the name of the delegated widget method
@param context: the S3DashboardContext'
| def do(self, command, context):
| widget = self.widget
msg = "%s does not expose a '%s' method"
exception = (lambda : NotImplementedError((msg % (widget.__class__.__name__, command))))
try:
method = getattr(widget, command)
except AttributeError:
raise exception()
if (type(method) is not delegat... |
'Build the widget XML for the context, and add it to the layout'
| def add_widget(self, layout, context):
| config = self.config
prototype = self.widget
contents = prototype.widget(self.agent_id, config, version=self.version, context=context)
configbar = prototype.configbar()
widget = DIV(configbar, contents, _class='db-widget', _id=self.agent_id)
prototype._load_script()
channel = config.get('cha... |
'Controller for the widget configuration dialog
@param dashboard: the calling S3Dashboard instance
@param context: the S3DashboardContext
@return: output dict for the view'
| def configure(self, dashboard, context):
| response = current.response
s3 = response.s3
prototype = self.widget
formfields = prototype.configure(self)
formdata = dict(self.config)
formdata['id'] = 0
T = current.T
submit_btn = INPUT(_class='tiny primary button submit-btn', _name='submit', _type='submit', _value=T('Submit'... |
'Construct the XML for this widget
@param agent_id: the agent ID (same as the DOM node ID of the
outer wrapper DIV, to attach scripts)
@param config: the active widget configuration
@param version: the config version key
@param context: the S3DashboardContext
@return: an XmlComponent with the widget contents,
the outer... | def widget(self, agent_id, config, version=None, context=None):
| contents = config.get('xml', '')
self.inject_script(agent_id, version=version)
return XML(contents)
|
'Get the path to the script file for this widget, can be
implemented in subclasses to override the default.
@param debug: whether running in debug mode or not
@return: path relative to static/scripts,
None if no separate script file required'
| def get_script_path(self, debug=False):
| return None
|
'Get widget-specific configuration form fields
@param agent: the agent
@return: a list of Fields for the form construction'
| def configure(self, agent):
| formfields = [Field('xml', 'text', label='XML')]
return formfields
|
'Extract the new config settings from the form and
update the config dict
@param config: the config dict
@param form: the configuration form
@return: the updated config dict (can be a replacement)
NB config must remain JSON-serializable'
| def accept_config(self, config, form):
| formvars = form.vars
xml = formvars.get('xml')
if (xml is not None):
config['xml'] = xml
return config
|
'Validation function for configuration form'
| def validate_config(self, form):
| pass
|
'Helper method to inject the init script for a particular agent,
usually called by widget() method.
@param agent_id: the agent ID
@param version: the config version key
@param widget_class: the widget class to instantiate
@param options: JSON-serializable dict of options to pass
to the widget instance'
| @classmethod
def inject_script(cls, agent_id, version=None, widget_class='dashboardWidget', options=None):
| s3 = current.response.s3
if ((not agent_id) or (not widget_class)):
return
if (not options):
options = {}
title = cls.title
if title:
options['title'] = s3_str(current.T(title))
dashboard_url = URL(args=[], vars={})
options['dashboardURL'] = dashboard_url
options[... |
'Build the widget configuration task bar
@return: the XML for the task bar'
| @staticmethod
def configbar():
| return DIV(SPAN(ICON('move', _class='db-task-move'), _class='db-configbar-left'), SPAN(ICON('delete', _class='db-task-delete'), ICON('settings', _class='db-task-config'), _class='db-configbar-right'), _class='db-configbar')
|
'Initialize the widget, called when configuring an available
widget for the dashboard.
@param label: a label for this widget type, used in the widget
selector in the configuration GUI; if left empty,
then the widget type will not appear in the selector
@param defaults: the default configuration for this widget
@param o... | def __init__(self, label=None, defaults=None, on_create_agent=None, **options):
| self.label = label
if (defaults is None):
defaults = {}
self.defaults = defaults
self.options = options
self.on_create_agent = on_create_agent
self.agents = {}
self.script_loaded = False
|
'Create an agent for this widget
@param agent_id: the agent ID
@param config: the agent configuration dict
@param version: the config version key
@param context: the current S3DashboardContext'
| def create_agent(self, agent_id, config=None, version=None, context=None):
| agent_config = dict(self.defaults)
if config:
agent_config.update(config)
agent = self.agents.get(agent_id)
if agent:
agent.config = agent_config
agent.version = version
else:
agent = S3DashboardAgent(agent_id, widget=self, config=agent_config, version=version)
... |
'Add the script file to s3.scripts, called when an agent
builds the widget'
| def _load_script(self):
| if self.script_loaded:
return
s3 = current.response.s3
scripts = s3.scripts
path = self.get_script_path(debug=s3.debug)
if path:
appname = current.request.application
script = ('/%s/static/scripts/%s' % (appname, path))
if (script not in scripts):
scripts.... |
'Constructor'
| def __init__(self, module=None):
| self.cache = (current.cache.ram, 60)
self.context = None
self.classes = Storage()
if (not hasattr(current, 'model')):
current.model = Storage(config=Storage(), components=Storage(), methods=Storage(), cmethods=Storage(), hierarchies=Storage())
response = current.response
if ('s3' not in ... |
'Model auto-loader'
| def __getattr__(self, name):
| return self.table(name, AttributeError(('undefined table: %s' % name)))
|
'Defines all tables in this model, to be implemented by
subclasses'
| def model(self):
| return None
|
'Definitions of model globals (response.s3.*) if the model
has been disabled in deployment settings, to be implemented
by subclasses'
| def defaults(self):
| return None
|
'Helper function to load a table definition by its name'
| @classmethod
def table(cls, tablename, default=None, db_only=False):
| s3 = current.response.s3
if (s3 is None):
s3 = current.response.s3 = Storage()
s3db = current.s3db
models = current.models
if (not db_only):
if (tablename in s3):
return s3[tablename]
elif ((s3db is not None) and (tablename in s3db.classes)):
(prefix, ... |
'Helper function to load a response.s3 variable from models'
| @classmethod
def get(cls, name, default=None):
| s3 = current.response.s3
if (s3 is None):
s3 = current.response.s3 = Storage()
if (name in s3):
return s3[name]
elif ('_' in name):
prefix = name.split('_', 1)[0]
models = current.models
if hasattr(models, prefix):
module = models.__dict__[prefix]
... |
'Helper function to load a model by its name (=prefix)'
| @classmethod
def load(cls, name):
| s3 = current.response.s3
if (s3 is None):
s3 = current.response.s3 = Storage()
models = current.models
if ((models is not None) and hasattr(models, name)):
module = models.__dict__[name]
for n in module.__all__:
model = module.__dict__[n]
if ((type(model).... |
'Helper function to load all models'
| @classmethod
def load_all_models(cls):
| s3 = current.response.s3
if s3.all_models_loaded:
return
s3.load_all_models = True
models = current.models
if (models is not None):
for name in models.__dict__:
if (type(models.__dict__[name]).__name__ == 'module'):
cls.load(name)
from s3import import ... |
'Same as db.define_table except that it does not repeat
a table definition if the table is already defined.'
| @classmethod
def define_table(cls, tablename, *fields, **args):
| db = current.db
if hasattr(db, tablename):
table = ogetattr(db, tablename)
else:
table = db.define_table(tablename, *fields, **args)
return table
|
'Wrapper for the S3Resource constructor to realize
the global s3db.resource() method'
| @staticmethod
def resource(tablename, *args, **kwargs):
| return S3Resource(tablename, *args, **kwargs)
|
'Update the extra configuration of a table
@param tablename: the name of the table
@param attr: dict of attributes to update'
| @classmethod
def configure(cls, tablename, **attr):
| config = current.model.config
tn = (tablename._tablename if (type(tablename) is Table) else tablename)
if (tn not in config):
config[tn] = Storage()
config[tn].update(attr)
return
|
'Reads a configuration attribute of a resource
@param tablename: the name of the resource DB table
@param key: the key (name) of the attribute'
| @classmethod
def get_config(cls, tablename, key, default=None):
| config = current.model.config
tn = (tablename._tablename if (type(tablename) is Table) else tablename)
if (tn in config):
return config[tn].get(key, default)
else:
return default
|
'Removes configuration attributes of a resource
@param table: the resource DB table
@param keys: keys of attributes to remove (maybe multiple)'
| @classmethod
def clear_config(cls, tablename, *keys):
| config = current.model.config
tn = (tablename._tablename if (type(tablename) is Table) else tablename)
if (tn in config):
if (not keys):
del config[tn]
else:
[config[tn].pop(k, None) for k in keys]
return
|
'Generic method to append a custom onvalidation|onaccept
callback to the originally configured callback chain,
for use in customise_* in templates
@param tablename: the table name
@param hook: the main hook ("onvalidation"|"onaccept")
@param cb: the custom callback function
@param method: the sub-hook ("create"|"update... | @classmethod
def add_custom_callback(cls, tablename, hook, cb, method=None):
| def extend(this, new):
if isinstance(this, (tuple, list)):
this = list(this)
elif (this is not None):
this = [this]
else:
this = []
if (new not in this):
this.append(new)
return this
callbacks = {}
for m in ('create', 'u... |
'Reverse-lookup of virtual references which are declared for
the respective lookup-table as:
configure(tablename,
referenced_by = [(tablename, fieldname), ...],
& in the table with the fields(auth_user only current example) as:
configure(tablename,
references = {fieldname: tablename,
@param field: the Field
@returns: t... | @classmethod
def virtual_reference(cls, field):
| if (str(field.type) == 'integer'):
config = current.model.config
(tablename, fieldname) = str(field).split('.')
this_config = config[tablename]
if this_config:
references = this_config.get('references')
if ((references is not None) and (fieldname in references... |
'Helper to run the onvalidation routine for a record
@param table: the Table
@param record: the FORM or the Row to validate
@param method: the method'
| @classmethod
def onaccept(cls, table, record, method='create'):
| if hasattr(table, '_tablename'):
tablename = table._tablename
else:
tablename = table
onaccept = cls.get_config(tablename, ('%s_onaccept' % method), cls.get_config(tablename, 'onaccept'))
if ('vars' not in record):
record = Storage(vars=Storage(record), errors=Storage())
if o... |
'Helper to run the onvalidation routine for a record
@param table: the Table
@param record: the FORM or the Row to validate
@param method: the method'
| @classmethod
def onvalidation(cls, table, record, method='create'):
| if hasattr(table, '_tablename'):
tablename = table._tablename
else:
tablename = table
onvalidation = cls.get_config(tablename, ('%s_onvalidation' % method), cls.get_config(tablename, 'onvalidation'))
if ('vars' not in record):
record = Storage(vars=Storage(record), errors=Storage... |
'Configure component links for a master table.
@param master: the name of the master table
@param links: component link configurations'
| @classmethod
def add_components(cls, master, **links):
| components = current.model.components
load_all_models = current.response.s3.load_all_models
master = (master._tablename if (type(master) is Table) else master)
hooks = components.get(master)
if (hooks is None):
hooks = Storage()
for (tablename, ll) in links.items():
(prefix, name... |
'Helper function to look up and declare dynamic components
for a table; called by get_components if dynamic_components
is configured for the table
@param tablename: the table name
@param exclude: names to exclude (static components)'
| @classmethod
def add_dynamic_components(cls, tablename, exclude=None):
| mtable = cls.table(tablename)
if (mtable is None):
return
if cls.get_config(tablename, 'dynamic_components_loaded'):
return
ttable = cls.table('s3_table')
ftable = cls.table('s3_field')
join = ttable.on((ttable.id == ftable.table_id))
query = (((ftable.master == tablename) & ... |
'Finds a component definition.
@param table: the primary table or table name
@param name: the component name (without prefix)'
| @classmethod
def get_component(cls, table, name):
| components = cls.get_components(table, names=name)
if (name in components):
return components[name]
else:
return None
|
'Finds components of a table
@param table: the table or table name
@param names: a list of components names to limit the search to,
None for all available components'
| @classmethod
def get_components(cls, table, names=None):
| components = current.model.components
load = cls.table
if (type(table) is Table):
tablename = table._tablename
else:
tablename = table
table = load(tablename)
if (table is None):
return None
single = False
if isinstance(names, str):
single = Tr... |
'Checks whether there are components defined for a table
@param table: the table or table name'
| @classmethod
def has_components(cls, table):
| components = current.model.components
load = cls.table
if (type(table) is Table):
tablename = table._tablename
else:
tablename = table
table = load(tablename)
if (table is None):
return False
if cls.get_config(tablename, 'dynamic_components'):
cls.... |
'DRY Helper method to filter component hooks
@param components: components already found, dict {alias: component}
@param hooks: component hooks to filter, dict {alias: hook}
@param names: the names (=aliases) to include
@param supertable: the super-table name to set for the component
@returns: set of names that could n... | @classmethod
def __get_hooks(cls, components, hooks, names=None, supertable=None):
| for alias in hooks:
if ((alias in components) or ((names is not None) and (alias not in names))):
continue
hook = hooks[alias]
hook['supertable'] = supertable
components[alias] = hook
return ((set(names) - set(hooks)) if (names is not None) else None)
|
'Find a component alias from the link table alias.
@param tablename: the name of the master table
@param link: the alias of the link table'
| @classmethod
def get_alias(cls, tablename, link):
| components = current.model.components
table = cls.table(tablename)
if (not table):
return None
def get_alias(hooks, link):
if (link[(-6):] == '__link'):
alias = link.rsplit('__link', 1)[0]
hook = hooks.get(alias)
if hook:
return alias
... |
'Get the alias of the component that represents the parent
node in a hierarchy (for link-table based hierarchies)
@param tablename: the table name
@returns: the alias of the hierarchy parent component'
| @classmethod
def hierarchy_link(cls, tablename):
| if (not cls.table(tablename, db_only=True)):
return None
hierarchy_link = cls.get_config(tablename, 'hierarchy_link')
if (not hierarchy_link):
hierarchy = cls.get_config(tablename, 'hierarchy')
if (hierarchy and ('.' in hierarchy)):
alias = hierarchy.rsplit('.', 1)[0]
... |
'Adds a custom method for a resource or component
@param prefix: prefix of the resource name (=module name)
@param name: name of the resource (=without prefix)
@param component_name: name of the component
@param method: name of the method
@param action: function to invoke for this method'
| @classmethod
def set_method(cls, prefix, name, component_name=None, method=None, action=None):
| methods = current.model.methods
cmethods = current.model.cmethods
if (not method):
raise SyntaxError('No method specified')
tablename = ('%s_%s' % (prefix, name))
if (not component_name):
if (method not in methods):
methods[method] = {}
methods[method][table... |
'Retrieves a custom method for a resource or component
@param prefix: prefix of the resource name (=module name)
@param name: name of the resource (=without prefix)
@param component_name: name of the component
@param method: name of the method'
| @classmethod
def get_method(cls, prefix, name, component_name=None, method=None):
| methods = current.model.methods
cmethods = current.model.cmethods
if (not method):
return None
tablename = ('%s_%s' % (prefix, name))
if (not component_name):
if ((method in methods) and (tablename in methods[method])):
return methods[method][tablename]
else:
... |
'Define a super-entity table
@param tablename: the tablename
@param key: name of the primary key
@param types: a dictionary of instance types
@param fields: any shared fields
@param args: table arguments (e.g. migrate)'
| @classmethod
def super_entity(cls, tablename, key, types, *fields, **args):
| db = current.db
if (db._dbname == 'postgres'):
sequence_name = ('%s_%s_seq' % (tablename, key))
else:
sequence_name = None
table = db.define_table(tablename, Field(key, 'id', readable=False, writable=False), Field('deleted', 'boolean', readable=False, writable=False, default=False), Fiel... |
'Get the name of the key for a super-entity
@param supertable: the super-entity table'
| @classmethod
def super_key(cls, supertable, default=None):
| if ((supertable is None) and default):
return default
if isinstance(supertable, str):
supertable = cls.table(supertable)
try:
return supertable._id.name
except AttributeError:
pass
raise SyntaxError(('No id-type key found in %s' % supertable._tablename)... |
'Get a foreign key field for a super-entity
@param supertable: the super-entity table
@param label: label for the field
@param comment: comment for the field
@param readable: set the field readable
@param represent: set a representation function for the field'
| @classmethod
def super_link(cls, name, supertable, label=None, comment=None, represent=None, orderby=None, sort=True, filterby=None, filter_opts=None, not_filterby=None, not_filter_opts=None, instance_types=None, realms=None, updateable=False, groupby=None, script=None, widget=None, empty=True, default=DEFAULT, ondelet... | if isinstance(supertable, str):
supertable = cls.table(supertable)
if (supertable is None):
if (name is not None):
return Field(name, 'integer', readable=False, writable=False)
else:
raise SyntaxError('Undefined super-entity')
else:
key = cls.super_... |
'Updates the super-entity links of an instance record
@param table: the instance table
@param record: the instance record'
| @classmethod
def update_super(cls, table, record):
| get_config = cls.get_config
tablename = table._tablename
supertables = get_config(tablename, 'super_entity')
if (not supertables):
return False
record_id = record.get('id', None)
if (not record_id):
return False
if (not isinstance(supertables, (list, tuple))):
superta... |
'Removes the super-entity links of an instance record
@param table: the instance table
@param record: the instance record
@return: True if successful, otherwise False (caller must
roll back the transaction if False is returned!)'
| @classmethod
def delete_super(cls, table, record):
| record_id = record.get(table._id.name, None)
if (not record_id):
raise RuntimeError('Record ID required for delete_super')
get_config = cls.get_config
supertables = get_config(table._tablename, 'super_entity')
if (not supertables):
return True
if (not isinstance(super... |
'Get prefix, name and ID of an instance record
@param supertable: the super-entity table
@param superid: the super-entity record ID
@return: a tuple (prefix, name, ID) of the instance
record (if it exists)'
| @classmethod
def get_instance(cls, supertable, superid):
| if (not hasattr(supertable, '_tablename')):
supertable = cls.table(supertable)
if (supertable is None):
return (None, None, None)
db = current.db
query = (supertable._id == superid)
entry = db(query).select(supertable.instance_type, supertable.uuid, limitby=(0, 1)).first()
if ent... |
'Constructor
@param tablename: the table name'
| def __init__(self, tablename):
| self.tablename = tablename
table = self.define_table(tablename)
if table:
self.table = table
else:
raise AttributeError(('Undefined dynamic model: %s' % tablename))
|
'Instantiate a dynamic Table
@param tablename: the table name
@return: a Table instance'
| def define_table(self, tablename):
| db = current.db
redefine = (tablename in db)
s3db = current.s3db
ttable = s3db.s3_table
ftable = s3db.s3_field
query = (((ttable.name == tablename) & (ttable.deleted != True)) & (ftable.table_id == ttable.id))
rows = db(query).select(ftable.name, ftable.field_type, ftable.label, ftable.requi... |
'Configure the table (e.g. CRUD strings)'
| @staticmethod
def _configure(tablename):
| s3db = current.s3db
ttable = s3db.s3_table
query = ((ttable.name == tablename) & (ttable.deleted != True))
row = current.db(query).select(ttable.title, ttable.settings, limitby=(0, 1)).first()
if row:
title = row.title
if title:
current.response.s3.crud_strings[tablename]... |
'Convert a s3_field Row into a Field instance
@param tablename: the table name
@param row: the s3_field Row
@return: a Field instance'
| @classmethod
def _field(cls, tablename, row):
| field = None
if row:
fieldtype = row.field_type
if row.options:
construct = cls._options_field
elif (fieldtype == 'date'):
construct = cls._date_field
elif (fieldtype == 'datetime'):
construct = cls._datetime_field
elif (fieldtype[:9] =... |
'Generic field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _generic_field(tablename, row):
| fieldname = row.name
fieldtype = row.field_type
if row.require_unique:
from s3validators import IS_NOT_ONE_OF
requires = IS_NOT_ONE_OF(current.db, ('%s.%s' % (tablename, fieldname)))
else:
requires = None
if (fieldtype in ('string', 'text')):
default = row.default_val... |
'Options-field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _options_field(tablename, row):
| fieldname = row.name
fieldtype = row.field_type
fieldopts = row.options
settings = (row.settings or {})
translate = settings.get('translate_options', True)
T = current.T
from s3utils import s3_str
sort = False
zero = ''
if isinstance(fieldopts, dict):
options = fieldopts
... |
'Date field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _date_field(tablename, row):
| fieldname = row.name
settings = (row.settings or {})
attr = {}
for keyword in ('past', 'future'):
setting = settings.get(keyword, DEFAULT)
if (setting is not DEFAULT):
attr[keyword] = setting
attr['empty'] = False
default = row.default_value
if default:
if... |
'DateTime field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _datetime_field(tablename, row):
| fieldname = row.name
settings = (row.settings or {})
attr = {}
for keyword in ('past', 'future'):
setting = settings.get(keyword, DEFAULT)
if (setting is not DEFAULT):
attr[keyword] = setting
attr['empty'] = False
default = row.default_value
if default:
if... |
'Reference field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _reference_field(tablename, row):
| fieldname = row.name
fieldtype = row.field_type
ktablename = fieldtype.split(' ', 1)[1].split('.', 1)[0]
ktable = current.s3db.table(ktablename)
if ktable:
from s3fields import S3Represent
from s3validators import IS_ONE_OF
if ('name' in ktable.fields):
represe... |
'Numeric field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _numeric_field(tablename, row):
| fieldname = row.name
fieldtype = row.field_type
settings = (row.settings or {})
minimum = settings.get('min')
maximum = settings.get('max')
if (fieldtype == 'integer'):
parse = int
requires = IS_INT_IN_RANGE(minimum=minimum, maximum=maximum)
elif (fieldtype == 'double'):
... |
'Boolean field constructor
@param tablename: the table name
@param row: the s3_field Row
@return: the Field instance'
| @staticmethod
def _boolean_field(tablename, row):
| fieldname = row.name
fieldtype = row.field_type
default = row.default_value
if default:
default = default.lower()
if (default == 'true'):
default = True
elif (default == 'none'):
default = None
else:
default = False
else:
de... |
'Register at the repository (does nothing in CommandBridge)
@return: True if successful, otherwise False'
| def register(self):
| return True
|
'Login to the repository (does nothing in CommandBridge)
@return: None if successful, otherwise error message'
| def login(self):
| return None
|
'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):
| error = 'CommandBridge API pull not implemented'
current.log.error(error)
return (error, None)
|
'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):
| xml = current.xml
repository = self.repository
resource_name = task.resource_name
current.log.debug(('S3SyncCommandBridge.push(%s, %s)' % (repository.url, resource_name)))
resource = current.s3db.resource(resource_name, include_deleted=True)
folder = current.request.folder
import os
s... |
'Send a request to the CommandBridge 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):
| xml = current.xml
repository = self.repository
url = repository.url.rstrip('/')
if path:
url = '/'.join((url, path.lstrip('/')))
if args:
url = '?'.join((url, urllib.urlencode(args)))
req = urllib2.Request(url=url)
handlers = []
site_key = repository.site_key
if (not ... |
'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):
| 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):
| repository = self.repository
log = repository.log
error = None
result = None
tablename = task.resource_name
if (tablename == 'mixed'):
resource = None
mixed = True
else:
try:
resource = current.s3db.resource(tablename)
except SyntaxError:
... |
'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
log = repository.log
error = None
result = None
tablename = task.resource_name
if (tablename == 'mixed'):
resource = None
mixed = True
else:
try:
resource = current.s3db.resource(tablename, include_deleted=True)
except ... |
'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):
| msg = 'Send not supported for this repository type'
return {'status': self.log.FATAL, 'remote': False, 'message': msg, 'response': None}
|
'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):
| msg = 'Receive not supported for this repository type'
return {'status': self.log.FATAL, 'remote': False, 'message': msg, 'response': None}
|
'Helper function to get all relevant input files from the
repository path, excluding files which have not been modified
since the last pull of the task
@param task: the synchronization task
@return: a list of file paths, ordered by their time
stamp (oldest first)'
| def _input_files(self, task):
| path = self.repository.path
if (not os.path.isabs(path)):
path = os.path.join(current.request.folder, path)
pattern = task.infile_pattern
if (path and pattern):
pattern = os.path.join(path, pattern)
else:
return []
all_files = glob.glob(pattern)
infiles = []
appen... |
'Helper function to construct the output file name from
the repository path and the output file name pattern
@param task: the synchronization task
@return: the output file name, or None if either
path or pattern are missing'
| def _output_file(self, task):
| path = self.repository.path
if (not os.path.isabs(path)):
path = os.path.join(current.request.folder, path)
pattern = task.outfile_pattern
if ((not path) or (not pattern)):
return None
from string import Template
template = Template(pattern).safe_substitute(year='%(y)04d', month=... |
'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):
| return None
|
'Outgoing pull
@param task: the task (sync_task Row)'
| def pull(self, task, onconflict=None):
| repository = self.repository
log = repository.log
PATH = os.path.join(current.request.folder, 'uploads', 'adashi_feeds')
try:
files_list = os.listdir(PATH)
except os.error:
message = 'Upload path does not exist or can not be accessed'
log.write(repo... |
'Outgoing push
@param task: the sync_task Row'
| def push(self, task):
| repository = self.repository
log = repository.log
log.write(repository_id=repository.id, resource_name=task.resource_name, transmission=log.OUT, mode=log.PUSH, action=None, remote=False, result=log.FATAL, message='Push to ADASHI currently not supported')
output = current.xml.json_message(... |
'Respond to an incoming pull from a 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
@param ... | 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)}
stylesheet = os.path.join(current.request.folder, 'static', 'formats', 'georss', 'export.xsl')
... |
'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):
| s3db = current.s3db
xml = current.xml
log = self.log
remote = False
source = source[0]
tree = xml.parse(source)
if (not tree):
msg = (xml.error if xml.error else 'Invalid source')
return {'status': log.FATAL, 'message': msg, 'remote': remote, 'response': xml.json_message(F... |
'Deactivate all previous unit assignments (event_team) for
an incident which are not in this feed update.
@param item: the import item
@note: this assumes that the list of incident resources in
the feed update is complete (confirmed for ADASHI)
@note: must not deactivate assignments which are newer
than the feed update... | def update_assignments(self, item):
| if ((item.tablename == 'event_incident') and item.id and (item.method == item.METHOD.UPDATE)):
job = item.job
mtime = item.data.get('modified_on')
if ((not job) or (not mtime)):
return
get_item = (lambda item_id: job.items.get(item_id))
team_names = set()
... |
'Helper method to store source data in file system
@param tree: the XML element tree of the source
@param category: the feed category'
| def keep_source(self, tree, category):
| repository = self.repository
log = repository.log
log.write(repository_id=repository.id, resource_name=None, transmission=log.IN, mode=log.PUSH, action='receive', remote=False, result=log.WARNING, message="'Keep Source Data' active for this repository!")
request = current.request
f... |
'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):
| _debug = current.log.debug
_debug('S3SyncCiviCRM.login()')
repository = self.repository
request = {'q': 'civicrm/login', 'name': repository.username, 'pass': repository.password}
(response, error) = self._send_request(**request)
if error:
_debug(('S3SyncCiviCRM.login FAILURE: %s' %... |
'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):
| xml = current.xml
_debug = current.log.debug
repository = self.repository
log = repository.log
resource_name = task.resource_name
_debug(('S3SyncCiviCRM.pull(%s, %s)' % (repository.url, resource_name)))
mtime = None
message = ''
remote = False
if (resource_name not in self.RES... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.