desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':param metadata: information needed to deserialize xml into a dictionary. :param xmlns: XML namespace to include with serialized xml'
def __init__(self, metadata=None, xmlns=None):
super(XMLDictSerializer, self).__init__() self.metadata = (metadata or {}) if (not xmlns): xmlns = self.metadata.get('xmlns') if (not xmlns): xmlns = constants.XML_NS_V20 self.xmlns = xmlns
':param data: expect data to contain a single key as XML root, or contain another \'*_links\' key as atom links. Other case will use \'VIRTUAL_ROOT_KEY\' as XML root.'
def default(self, data):
try: links = None has_atom = False if (data is None): root_key = constants.VIRTUAL_ROOT_KEY root_value = None else: link_keys = [k for k in (data.iterkeys() or []) if k.endswith('_links')] if link_keys: links = data.pop(...
'Recursive method to convert data members to XML nodes.'
def _to_xml_node(self, parent, metadata, nodename, data, used_prefixes):
result = etree.SubElement(parent, nodename) if (':' in nodename): used_prefixes.append(nodename.split(':', 1)[0]) if isinstance(data, list): if (not data): result.set(constants.TYPE_ATTR, constants.TYPE_LIST) return result singular = metadata.get('plurals', {}...
'Serialize a dict into a string and wrap in a wsgi.Request object. :param response_data: dict produced by the Controller :param content_type: expected mimetype of serialized response body'
def serialize(self, response_data, content_type, action='default'):
response = webob.Response() self.serialize_headers(response, response_data, action) self.serialize_body(response, response_data, content_type, action) return response
':param metadata: information needed to deserialize xml into a dictionary.'
def __init__(self, metadata=None):
super(XMLDeserializer, self).__init__() self.metadata = (metadata or {}) xmlns = self.metadata.get('xmlns') if (not xmlns): xmlns = constants.XML_NS_V20 self.xmlns = xmlns
'Convert a minidom node to a simple Python type. :param listnames: list of XML node names whose subnodes should be considered list items.'
def _from_xml_node(self, node, listnames):
attrNil = node.get(str(etree.QName(constants.XSI_NAMESPACE, 'nil'))) attrType = node.get(str(etree.QName(self.metadata.get('xmlns'), 'type'))) if (attrNil and (attrNil.lower() == 'true')): return None elif ((not len(node)) and (not node.text)): if (attrType and (attrType == constants.TYP...
'Extract necessary pieces of the request. :param request: Request object :returns tuple of expected controller action name, dictionary of keyword arguments to pass to the controller, the expected content type of the response'
def deserialize(self, request):
action_args = self.get_action_args(request.environ) action = action_args.pop('action', None) action_args.update(self.deserialize_headers(request, action)) action_args.update(self.deserialize_body(request, action)) accept = self.get_expected_content_type(request) return (action, action_args, acce...
'Parse dictionary created by routes library.'
def get_action_args(self, request_environment):
try: args = request_environment['wsgiorg.routing_args'][1].copy() except Exception: return {} try: del args['controller'] except KeyError: pass try: del args['format'] except KeyError: pass return args
'Used for paste app factories in paste.deploy config files. Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs. A hypothetical configuration would look like: [app:wadl] latest_version = 1.3 paste.app_factory = nova.api.fancy_...
@classmethod def factory(cls, global_config, **local_config):
return cls(**local_config)
'Subclasses will probably want to implement __call__ like this: @webob.dec.wsgify(RequestClass=Request) def __call__(self, req): # Any of the following objects work as responses: # Option 1: simple string res = \'message\n\' # Option 2: a nicely formatted HTTP exception page res = exc.HTTPForbidden(detail=\'Nice try\')...
def __call__(self, environ, start_response):
raise NotImplementedError(_('You must implement __call__'))
'Iterator that prints the contents of a wrapper string iterator when iterated.'
@staticmethod def print_generator(app_iter):
print (('*' * 40) + ' BODY') for part in app_iter: sys.stdout.write(part) sys.stdout.flush() (yield part) print
'Returns an instance of the WSGI Router class'
@classmethod def factory(cls, global_config, **local_config):
return cls()
'Create a router for the given routes.Mapper. Each route in `mapper` must specify a \'controller\', which is a WSGI app to call. You\'ll probably want to specify an \'action\' as well and have your controller be a wsgi.Controller, who will route the request to the action method. Examples: mapper = routes.Mapper() sc =...
def __init__(self, mapper):
self.map = mapper self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map)
'Route the incoming request to a controller based on self.map. If no match, return a 404.'
@webob.dec.wsgify def __call__(self, req):
return self._router
'Called by self._router after matching the incoming request to a route and putting the information into req.environ. Either returns 404 or the routed WSGI app\'s response.'
@staticmethod @webob.dec.wsgify def _dispatch(req):
match = req.environ['wsgiorg.routing_args'][1] if (not match): return webob.exc.HTTPNotFound() app = match['controller'] return app
':param controller: object that implement methods created by routes lib :param deserializer: object that can serialize the output of a controller into a webob response :param serializer: object that can deserialize a webob request into necessary pieces :param fault_body_function: a function that will build the response...
def __init__(self, controller, fault_body_function, deserializer=None, serializer=None):
self.controller = controller self.deserializer = (deserializer or RequestDeserializer()) self.serializer = (serializer or ResponseSerializer()) self._fault_body_function = fault_body_function xml_serializer = self.serializer.body_serializers['application/xml'] if hasattr(xml_serializer, 'xmlns')...
'WSGI method that controls (de)serialization and method dispatch.'
@webob.dec.wsgify(RequestClass=Request) def __call__(self, request):
LOG.info(_('%(method)s %(url)s'), {'method': request.method, 'url': request.url}) try: (action, args, accept) = self.deserializer.deserialize(request) except exception.InvalidContentType: msg = _('Unsupported Content-Type') LOG.exception(_('InvalidContentType: %s'), msg) ...
'Find action-spefic method on controller and call it.'
def dispatch(self, request, action, action_args):
controller_method = getattr(self.controller, action) try: return controller_method(request=request, **action_args) except TypeError as exc: LOG.exception(exc) return Fault(webob.exc.HTTPBadRequest(), self._xmlns)
'Creates a Fault for the given webob.exc.exception.'
def __init__(self, exception, xmlns=None, body_function=None):
self.wrapped_exc = exception self.status_int = self.wrapped_exc.status_int self._xmlns = xmlns self._body_function = (body_function or _default_body_function)
'Generate a WSGI response based on the exception passed to ctor.'
@webob.dec.wsgify(RequestClass=Request) def __call__(self, req):
(fault_data, metadata) = self._body_function(self.wrapped_exc) xml_serializer = XMLDictSerializer(metadata, self._xmlns) content_type = req.best_match_content_type() serializer = {'application/xml': xml_serializer, 'application/json': JSONDictSerializer()}[content_type] self.wrapped_exc.body = seria...
'Call the method specified in req.environ by RoutesMiddleware.'
@webob.dec.wsgify(RequestClass=Request) def __call__(self, req):
arg_dict = req.environ['wsgiorg.routing_args'][1] action = arg_dict['action'] method = getattr(self, action) del arg_dict['controller'] del arg_dict['action'] if ('format' in arg_dict): del arg_dict['format'] arg_dict['request'] = req result = method(**arg_dict) if (isinstanc...
'Serialize the given dict to the provided content_type. Uses self._serialization_metadata if it exists, which is a dict mapping MIME types to information needed to serialize to that type.'
def _serialize(self, data, content_type, default_xmlns):
_metadata = getattr(type(self), '_serialization_metadata', {}) serializer = Serializer(_metadata, default_xmlns) try: return serializer.serialize(data, content_type) except exception.InvalidContentType: raise webob.exc.HTTPNotAcceptable()
'Deserialize the request body to the specefied content type. Uses self._serialization_metadata if it exists, which is a dict mapping MIME types to information needed to serialize to that type.'
def _deserialize(self, data, content_type):
_metadata = getattr(type(self), '_serialization_metadata', {}) serializer = Serializer(_metadata) return serializer.deserialize(data, content_type)['body']
'Provide the XML namespace to use if none is otherwise specified.'
def get_default_xmlns(self, req):
return None
'Create a serializer based on the given WSGI environment. \'metadata\' is an optional dict mapping MIME types to information needed to serialize a dictionary to that type.'
def __init__(self, metadata=None, default_xmlns=None):
self.metadata = (metadata or {}) self.default_xmlns = default_xmlns
'Serialize a dictionary into the specified content type.'
def serialize(self, data, content_type):
return self._get_serialize_handler(content_type).serialize(data)
'Deserialize a string to a dictionary. The string must be in the format of a supported MIME type.'
def deserialize(self, datastring, content_type):
try: return self.get_deserialize_handler(content_type).deserialize(datastring) except Exception: raise webob.exc.HTTPBadRequest(_('Could not deserialize data'))
'Schedule the network to an active DHCP agent if there is no active DHCP agent hosting it.'
def schedule(self, plugin, context, network):
with context.session.begin(subtransactions=True): dhcp_agents = plugin.get_dhcp_agents_hosting_networks(context, [network['id']], active=True) if dhcp_agents: LOG.debug(_('Network %s is hosted already'), network['id']) return enabled_dhcp_agents = plugin.g...
'Schedule non-hosted networks to the DHCP agent on the specified host.'
def auto_schedule_networks(self, plugin, context, host):
with context.session.begin(subtransactions=True): query = context.session.query(agents_db.Agent) query = query.filter((agents_db.Agent.agent_type == constants.AGENT_TYPE_DHCP), (agents_db.Agent.host == host), (agents_db.Agent.admin_state_up == True)) try: dhcp_agent = query.one()...
'Schedule non-hosted routers to L3 Agent running on host. If router_id is given, only this router is scheduled if it is not hosted yet. Don\'t schedule the routers which are hosted already by active l3 agents.'
def auto_schedule_routers(self, plugin, context, host, router_id):
with context.session.begin(subtransactions=True): query = context.session.query(agents_db.Agent) query = query.filter((agents_db.Agent.agent_type == constants.AGENT_TYPE_L3), (agents_db.Agent.host == host), (agents_db.Agent.admin_state_up == True)) try: l3_agent = query.one() ...
'Schedule the router to an active L3 agent if there is no enable L3 agent hosting it.'
def schedule(self, plugin, context, sync_router):
with context.session.begin(subtransactions=True): l3_agents = plugin.get_l3_agents_hosting_routers(context, [sync_router['id']], admin_state_up=True) if l3_agents: LOG.debug(_('Router %(router_id)s has already been hosted by L3 agent %(agent_id)s'), {'router_id...
':param read_deleted: \'no\' indicates deleted records are hidden, \'yes\' indicates deleted records are visible, \'only\' indicates that *only* deleted records are visible.'
def __init__(self, user_id, tenant_id, is_admin=None, read_deleted='no', roles=None, timestamp=None, **kwargs):
if kwargs: LOG.warn(_('Arguments dropped when creating context: %s'), kwargs) super(ContextBase, self).__init__(user=user_id, tenant=tenant_id, is_admin=is_admin) self.roles = (roles or []) if (self.is_admin is None): self.is_admin = ('admin' in [x.lower() for x in self.ro...
'Return a version of this context with admin flag set.'
def elevated(self, read_deleted=None):
context = copy.copy(self) context.is_admin = True if ('admin' not in [x.lower() for x in context.roles]): context.roles.append('admin') if (read_deleted is not None): context.read_deleted = read_deleted return context
'Only check that the first argument (command) matches exec_path'
def match(self, userargs):
return (os.path.basename(self.exec_path) == userargs[0])
'Returns command to execute (with sudo -u if run_as != root).'
def get_command(self, userargs):
if (self.run_as != 'root'): return (['sudo', '-u', self.run_as, self.exec_path] + userargs[1:]) return ([self.exec_path] + userargs[1:])
'Returns specific environment to set, None if none'
def get_environment(self, userargs):
return None
'This matches the combination of the leading env vars plus "dnsmasq"'
def match(self, userargs):
if (self.is_dnsmasq_env_vars(userargs) and self.is_dnsmasq_cmd(userargs[2:])): return True return False
'This matches the combination of the leading env vars plus "ip" "netns" "exec" <foo> "dnsmasq"'
def match(self, userargs):
if (self.is_dnsmasq_env_vars(userargs) and self.is_ip_netns_cmd(userargs[2:]) and self.is_dnsmasq_cmd(userargs[6:])): return True return False
'Returns the help text for this step.'
def get_help_text(self, extra_context=None):
text = '' extra_context = (extra_context or {}) if self.help_text_template: tmpl = template.loader.get_template(self.help_text_template) context = template.RequestContext(self.request, extra_context) text += tmpl.render(context) else: text += linebreaks(force_unicode(self...
'Adds an error to the Action\'s Step based on API issues.'
def add_error(self, message):
self._get_errors()[NON_FIELD_ERRORS] = self.error_class([message])
'Handles any requisite processing for this action. The method should return either ``None`` or a dictionary of data to be passed to :meth:`~horizon.workflows.Step.contribute`. Returns ``None`` by default, effectively making it a no-op.'
def handle(self, request, context):
return None
'Allows for customization of how the workflow context is passed to the action; this is the reverse of what "contribute" does to make the action outputs sane for the workflow. Changes to the context are not saved globally here. They are localized to the action. Simply returns the unaltered context by default.'
def prepare_action_context(self, request, context):
return context
'Returns the ID for this step. Suitable for use in HTML markup.'
def get_id(self):
return ('%s__%s' % (self.workflow.slug, self.slug))
'Adds the data listed in ``contributes`` to the workflow\'s shared context. By default, the context is simply updated with all the data returned by the action. Note that even if the value of one of the ``contributes`` keys is not present (e.g. optional) the key should still be added to the context with a value of ``Non...
def contribute(self, data, context):
if data: for key in self.contributes: context[key] = data.get(key, None) return context
'Renders the step.'
def render(self):
step_template = template.loader.get_template(self.template_name) extra_context = {'form': self.action, 'step': self} context = template.RequestContext(self.workflow.request, extra_context) return step_template.render(context)
'Returns the help text for this step.'
def get_help_text(self):
text = linebreaks(force_unicode(self.help_text)) text += self.action.get_help_text() return safe(text)
'Adds an error to the Step based on API issues.'
def add_error(self, message):
self.action.add_error(message)
'Returns the instantiated step matching the given slug.'
def get_step(self, slug):
for step in self.steps: if (step.slug == slug): return step
'Returns the slug of the step which the workflow should begin on. This method takes into account both already-available data and errors within the steps.'
def get_entry_point(self):
if self.entry_point: if self.get_step(self.entry_point): return self.entry_point for step in self.steps: if step.has_errors: return step.slug try: step._verify_contributions(self.context) except exceptions.WorkflowError: return step...
'Registers a :class:`~horizon.workflows.Step` with the workflow.'
@classmethod def register(cls, step_class):
if (not inspect.isclass(step_class)): raise ValueError('Only classes may be registered.') elif (not issubclass(step_class, cls._registerable_class)): raise ValueError(('Only %s classes or subclasses may be registered.' % cls._registerable_class.__name__)) if ...
'Unregisters a :class:`~horizon.workflows.Step` from the workflow.'
@classmethod def unregister(cls, step_class):
try: cls._cls_registry.remove(step_class) except KeyError: raise base.NotRegistered(('%s is not registered' % cls)) return cls._unregister(step_class)
'Hook for custom context data validation. Should return a boolean value or raise :class:`~horizon.exceptions.WorkflowValidationError`.'
def validate(self, context):
return True
'Verified that all required data is present in the context and calls the ``validate`` method to allow for finer-grained checks on the context data.'
def is_valid(self):
missing = (self.depends_on - set(self.context.keys())) if missing: raise exceptions.WorkflowValidationError(('Unable to complete the workflow. The values %s are required but not present.' % ', '.join(missing))) steps_valid = True for step in self.steps: ...
'Finalizes a workflow by running through all the actions in order and calling their ``handle`` methods. Returns ``True`` on full success, or ``False`` for a partial success, e.g. there were non-critical errors. (If it failed completely the function wouldn\'t return.)'
def finalize(self):
partial = False for step in self.steps: try: data = step.action.handle(self.request, self.context) if ((data is True) or (data is None)): continue elif (data is False): partial = True else: self.context = ste...
'Handles any final processing for this workflow. Should return a boolean value indicating success.'
def handle(self, request, context):
return True
'Returns a URL to redirect the user to upon completion. By default it will attempt to parse a ``success_url`` attribute on the workflow, which can take the form of a reversible URL pattern name, or a standard HTTP URL.'
def get_success_url(self):
try: return urlresolvers.reverse(self.success_url) except urlresolvers.NoReverseMatch: return self.success_url
'Hook to allow customization of the message returned to the user upon successful or unsuccessful completion of the workflow. By default it simply inserts the workflow\'s name into the message string.'
def format_status_message(self, message):
if ('%s' in message): return (message % self.name) else: return message
'Renders the workflow.'
def render(self):
workflow_template = template.loader.get_template(self.template_name) extra_context = {'workflow': self} if self.request.is_ajax(): extra_context['modal'] = True context = template.RequestContext(self.request, extra_context) return workflow_template.render(context)
'Returns the canonical URL for this workflow. This is used for the POST action attribute on the form element wrapping the workflow. For convenience it defaults to the value of ``request.get_full_path()`` with any query string stripped off, e.g. the path at which the workflow was requested.'
def get_absolute_url(self):
return self.request.get_full_path().partition('?')[0]
'Adds an error to the workflow\'s Step with the specifed slug based on API issues. This is useful when you wish for API errors to appear as errors on the form rather than using the messages framework.'
def add_error_to_step(self, message, slug):
step = self.get_step(slug) if step: step.add_error(message)
'Returns initial data for the workflow. Defaults to using the GET parameters to allow pre-seeding of the workflow context values.'
def get_initial(self):
return copy.copy(self.request.GET)
'Returns the instanciated workflow class.'
def get_workflow(self):
extra_context = self.get_initial() entry_point = self.request.GET.get('step', None) workflow = self.workflow_class(self.request, context_seed=extra_context, entry_point=entry_point) return workflow
'Returns the template context, including the workflow class. This method should be overridden in subclasses to provide additional context data to the template.'
def get_context_data(self, **kwargs):
context = super(WorkflowView, self).get_context_data(**kwargs) workflow = self.get_workflow() context[self.context_object_name] = workflow next = self.request.REQUEST.get(workflow.redirect_param_name, None) context['REDIRECT_URL'] = next if self.request.is_ajax(): context['modal'] = True...
'Returns the template name to use for this request.'
def get_template_names(self):
if self.request.is_ajax(): template = self.ajax_template_name else: template = self.template_name return template
'Handler for HTTP GET requests.'
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs) self.set_workflow_step_errors(context) return self.render_to_response(context)
'Handler for HTTP POST requests.'
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs) workflow = context[self.context_object_name] if workflow.is_valid(): try: success = workflow.finalize() except: success = False exceptions.handle(request) next = self.request.REQUEST.get(workflow.redirect_p...
'Returns the raw data for this column, before any filters or formatting are applied to it. This is useful when doing calculations on data in the table.'
def get_raw_data(self, datum):
if callable(self.transform): data = self.transform(datum) elif hasattr(datum, self.transform): data = getattr(datum, self.transform, None) elif (isinstance(datum, collections.Iterable) and (self.transform in datum)): data = datum.get(self.transform) else: if settings.DEBU...
'Returns the final display data for this column from the given inputs. The return value will be either the attribute specified for this column or the return value of the attr:`~horizon.tables.Column.transform` method for this column.'
def get_data(self, datum):
datum_id = self.table.get_object_id(datum) if (datum_id in self.table._data_cache[self]): return self.table._data_cache[self][datum_id] data = self.get_raw_data(datum) display_value = None if self.display_choices: display_value = [display for (value, display) in self.display_choices ...
'Returns the final value for the column\'s ``link`` property. If ``allowed_data_types`` of this column is not empty and the datum has an assigned type, check if the datum\'s type is in the ``allowed_data_types`` list. If not, the datum won\'t be displayed as a link. If ``link`` is a callable, it will be passed the cur...
def get_link_url(self, datum):
if self.allowed_data_types: data_type_name = self.table._meta.data_type_name data_type = getattr(datum, data_type_name, None) if (data_type and (data_type not in self.allowed_data_types)): return None obj_id = self.table.get_object_id(datum) if callable(self.link): ...
'Returns the summary value for the data in this column if a valid summation method is specified for it. Otherwise returns ``None``.'
def get_summation(self):
if (self.summation not in self.summation_methods): return None summation_function = self.summation_methods[self.summation] data = [self.get_raw_data(datum) for datum in self.table.data] data = filter((lambda datum: (datum is not None)), data) if len(data): summation = summation_funct...
'Load the row\'s data (either provided at initialization or as an argument to this function), initiailize all the cells contained by this row, and set the appropriate row properties which require the row\'s data to be determined. This function is called automatically by :meth:`~horizon.tables.Row.__init__` if the ``dat...
def load_cells(self, datum=None):
table = self.table if datum: self.datum = datum else: datum = self.datum cells = [] for column in table.columns.values(): if (column.auto == 'multi_select'): widget = forms.CheckboxInput(check_test=False) data = widget.render('object_ids', unicode(tabl...
'Returns the bound cells for this row in order.'
def get_cells(self):
return self.cells.values()
'Fetches the updated data for the row based on the object id passed in. Must be implemented by a subclass to allow AJAX updating.'
def get_data(self, request, obj_id):
raise NotImplementedError(('You must define a get_data method on %s' % self.__class__.__name__))
'Returns a formatted version of the data for final output. This takes into consideration the :attr:`~horizon.tables.Column.link`` and :attr:`~horizon.tables.Column.empty_value` attributes.'
@property def value(self):
try: data = self.column.get_data(self.datum) if (data is None): if callable(self.column.empty_value): data = self.column.empty_value(self.datum) else: data = self.column.empty_value except: data = None exc_info = sys.exc_inf...
'Gets the status for the column based on the cell\'s data.'
@property def status(self):
if hasattr(self, '_status'): return self._status if (self.column.status or (self.column.name in self.column.table._meta.status_columns)): data_value_lower = unicode(self.data).lower() for (status_name, status_value) in self.column.status_choices: if (unicode(status_name).lowe...
'Returns a css class name determined by the status value.'
def get_status_class(self, status):
if (status is True): return 'status_up' elif (status is False): return 'status_down' else: return 'status_unknown'
'Returns a flattened string of the cell\'s CSS classes.'
def get_default_classes(self):
if (not self.url): self.column.classes = [cls for cls in self.column.classes if (cls != 'anchor')] column_class_string = self.column.get_final_attrs().get('class', '') classes = set(column_class_string.split(' ')) if self.column.status: classes.add(self.get_status_class(self.status)) ...
'Renders the table using the template from the table options.'
def render(self):
table_template = template.loader.get_template(self._meta.template) extra_context = {self._meta.context_var_name: self} context = template.RequestContext(self.request, extra_context) return table_template.render(context)
'Returns the canonical URL for this table. This is used for the POST action attribute on the form element wrapping the table. In many cases it is also useful for redirecting after a successful action on the table. For convenience it defaults to the value of ``request.get_full_path()`` with any query string stripped off...
def get_absolute_url(self):
return self.request.get_full_path().partition('?')[0]
'Returns the message to be displayed when there is no data.'
def get_empty_message(self):
return self._no_data_message
'Returns the data object from the table\'s dataset which matches the ``lookup`` parameter specified. An error will be raised if the match is not a single data object. Uses :meth:`~horizon.tables.DataTable.get_object_id` internally.'
def get_object_by_id(self, lookup):
matches = [datum for datum in self.data if (self.get_object_id(datum) == lookup)] if (len(matches) > 1): raise ValueError(('Multiple matches were returned for that id: %s.' % matches)) if (not matches): raise exceptions.Http302(self.get_absolute_url(), (_('No match ...
'Boolean. Indicates whether there are any available actions on this table.'
@property def has_actions(self):
if (not self.base_actions): return False return (any(self.get_table_actions()) or any(self._meta.row_actions))
'Boolean. Indicates whather this table should be rendered wrapped in a ``<form>`` tag or not.'
@property def needs_form_wrapper(self):
if (self._needs_form_wrapper is not None): return self._needs_form_wrapper return self.has_actions
'Returns a list of the action instances for this table.'
def get_table_actions(self):
bound_actions = [self.base_actions[action.name] for action in self._meta.table_actions] return [action for action in bound_actions if self._filter_action(action, self.request)]
'Returns a list of the action instances for a specific row.'
def get_row_actions(self, datum):
bound_actions = [] for action in self._meta.row_actions: bound_action = copy.copy(self.base_actions[action.name]) bound_action.attrs = copy.copy(bound_action.attrs) bound_action.datum = datum if (not self._filter_action(bound_action, self.request, datum)): continue ...
'Renders the actions specified in ``Meta.table_actions``.'
def render_table_actions(self):
template_path = self._meta.table_actions_template table_actions_template = template.loader.get_template(template_path) bound_actions = self.get_table_actions() extra_context = {'table_actions': bound_actions} if (self._meta.filter and self._filter_action(self._meta._filter_action, self.request)): ...
'Renders the actions specified in ``Meta.row_actions`` using the current row data.'
def render_row_actions(self, datum):
template_path = self._meta.row_actions_template row_actions_template = template.loader.get_template(template_path) bound_actions = self.get_row_actions(datum) extra_context = {'row_actions': bound_actions, 'row_id': self.get_object_id(datum)} context = template.RequestContext(self.request, extra_con...
'Parses the ``action`` parameter (a string) sent back with the POST data. By default this parses a string formatted as ``{{ table_name }}__{{ action_name }}__{{ row_id }}`` and returns each of the pieces. The ``row_id`` is optional.'
@staticmethod def parse_action(action_string):
if action_string: bits = action_string.split(STRING_SEPARATOR) bits.reverse() table = bits.pop() action = bits.pop() try: object_id = bits.pop() except IndexError: object_id = None return (table, action, object_id)
'Locates the appropriate action and routes the object data to it. The action should return an HTTP redirect if successful, or a value which evaluates to ``False`` if unsuccessful.'
def take_action(self, action_name, obj_id=None, obj_ids=None):
obj_ids = (obj_ids or self.request.POST.getlist('object_ids')) action = self.base_actions.get(action_name, None) if ((not action) or (action.method != self.request.method)): return None if ((not action.requires_input) or obj_id or obj_ids): if obj_id: obj_id = self.sanitize_i...
'Determine whether the request should be handled by this table.'
@classmethod def check_handler(cls, request):
if ((request.method == 'POST') and ('action' in request.POST)): (table, action, obj_id) = cls.parse_action(request.POST['action']) elif (('table' in request.GET) and ('action' in request.GET)): table = request.GET['table'] action = request.GET['action'] obj_id = request.GET.get('...
'Determine whether the request should be handled by a preemptive action on this table or by an AJAX row update before loading any data.'
def maybe_preempt(self):
request = self.request (table_name, action_name, obj_id) = self.check_handler(request) if (table_name == self.name): new_row = self._meta.row_class(self) if (new_row.ajax and (new_row.ajax_action_name == action_name)): try: datum = new_row.get_data(request, obj_id...
'Determine whether the request should be handled by any action on this table after data has been loaded.'
def maybe_handle(self):
request = self.request (table_name, action_name, obj_id) = self.check_handler(request) if ((table_name == self.name) and action_name): return self.take_action(action_name, obj_id) return None
'Override to modify an incoming obj_id to match existing API data types or modify the format.'
def sanitize_id(self, obj_id):
return obj_id
'Returns the identifier for the object this row will represent. By default this returns an ``id`` attribute on the given object, but this can be overridden to return other values. .. warning:: Make sure that the value returned is a unique value for the id otherwise rendering issues can occur.'
def get_object_id(self, datum):
return datum.id
'Returns a display name that identifies this object. By default, this returns a ``name`` attribute from the given object, but this can be overriden to return other values.'
def get_object_display(self, datum):
return datum.name
'Returns a boolean value indicating whether there is more data available to this table from the source (generally an API). The method is largely meant for internal use, but if you want to override it to provide custom behavior you can do so at your own risk.'
def has_more_data(self):
return self._meta.has_more_data
'Returns the identifier for the last object in the current data set for APIs that use marker/limit-based paging.'
def get_marker(self):
return http.urlquote_plus(self.get_object_id(self.data[(-1)]))
'Returns the query parameter string to paginate this table.'
def get_pagination_string(self):
return '='.join([self._meta.pagination_param, self.get_marker()])
'Returns a boolean value determining the overall row status based on the dictionary of column name to status mappings passed in. By default, it uses the following logic: #. If any statuses are ``False``, return ``False``. #. If no statuses are ``False`` but any or ``None``, return ``None``. #. If all statuses are ``Tru...
def calculate_row_status(self, statuses):
values = statuses.values() if any([(status is False) for status in values]): return False elif any([(status is None) for status in values]): return None else: return True
'Returns a css class name determined by the status value. This class name is used to indicate the status of the rows in the table if any ``status_columns`` have been specified.'
def get_row_status_class(self, status):
if (status is True): return 'status_up' elif (status is False): return 'status_down' else: return 'status_unknown'