code stringlengths 1 18.2k |
|---|
def create_cmd(self, args): ''' 'create' sub-command :param args: cli arguments :return: ''' cmd = args.get('cmd_create') if cmd == 'conf': conf_file = args['conf_file'] conf_id = args['id'] return self.load_xml_conf(conf_file, conf_id) else: print("Error: Create %s is invalid or not implemented" % cmd) |
def close(self, *args, **kwargs): """ write close tag of MRV file and close opened file :param force: force closing of externally opened file or buffer """ if not self.__finalized: self._file.write('</cml>') self.__finalized = True super().close(*args, **kwargs) |
def write(self, data): """ write single molecule or reaction into file """ self._file.write('<cml>') self.__write(data) self.write = self.__write |
def _load_cache(self): """ the method is implemented for the purpose of optimization, byte positions will not be re-read from a file that has already been used, if the content of the file has changed, and the name has been left the same, the old version of byte offsets will be loaded :return: list of byte offsets from ... |
as f: return load(f) except FileNotFoundError: return except IsADirectoryError as e: raise IsADirectoryError(f'Please delete {self.__cache_path} directory') from e except (UnpicklingError, EOFError) as e: raise UnpicklingError(f'Invalid cache file {self.__cache_path}. Please delete it') from e |
def _dump_cache(self, _shifts): """ _shifts dumps in /tmp directory after reboot it will drop """ with open(self.__cache_path, 'wb') as f: dump(_shifts, f) |
def get_task_types(current): """ List task types for current user .. code-block:: python # request: { 'view': '_zops_get_task_types', } # response: { 'task_types': [ {'name': string, # wf name 'title': string, # title of workflow },] } """ current.output['task_types'] = [{'name': bpmn_wf.name, 'title': bpmn_wf.title} f... |
def get_task_detail(current): """ Show task details .. code-block:: python # request: { 'view': '_zops_get_task_detail', 'key': key, } # response: { 'task_title': string, 'task_detail': string, # markdown formatted text } """ task_inv = TaskInvitation.objects.get(current.input['key']) obj = task_inv.instance.get_object... |
def get_task_actions(current): """ List task types for current user .. code-block:: python # request: { 'view': '_zops_get_task_actions', 'key': key, } # response: { 'key': key, 'actions': [{"title":':'Action Title', "wf": "workflow_name"},] } """ task_inv = TaskInvitation.objects.get(current.input['key']) actions = [{... |
= actions |
def get_tasks(current): """ List task invitations of current user .. code-block:: python # request: { 'view': '_zops_get_tasks', 'state': string, # one of these: # "active", "future", "finished", "expired" 'inverted': boolean, # search on other people's tasks 'query': string, # optional. for searching on user's tasks '... |
this date 'finish_date': datetime, # optional. only show tasks should end before this date } # response: { 'task_list': [ {'token': key, # wf token (key of WFInstance) {'key': key, # wf token (key of TaskInvitation) 'title': string, # name of workflow 'wf_type': string, # unread message count 'title': string, # task ti... |
start date 'finish_date': string, # end date },], 'active_task_count': int, 'future_task_count': int, 'finished_task_count': int, 'expired_task_count': int, } """ # TODO: Also return invitations for user's other roles # TODO: Handle automatic role switching STATE_DICT = { 'active': [20, 30], 'future': 10, 'finished': 4... |
show other user's tasks allowed_workflows = [bpmn_wf.name for bpmn_wf in BPMNWorkflow.objects.all() if current.has_permission(bpmn_wf.name)] queryset = queryset.exclude(role_id=current.role_id).filter(wf_name__in=allowed_workflows) else: # show current user's tasks queryset = queryset.filter(role_id=current.role_id) if... |
inv.title, 'wf_type': inv.wf_name, 'state': inv.progress, 'start_date': format_date(inv.start_date), 'finish_date': format_date(inv.finish_date), 'description': inv.instance.wf.description, 'status': inv.ownership} for inv in queryset ] task_inv_list = TaskInvitation.objects.filter(role_id=current.role_id) current.outp... |
def reduce_memory_usage(df): """reduce memory usage of the dataframe - convert runIDs to categorical - downcast ints and floats """ usage_pre = df.memory_usage(deep=True).sum() if "runIDs" in df: df.loc[:, "runIDs"] = df.loc[:, "runIDs"].astype("category") df_int = df.select_dtypes(include=['int']) df_float = df.select... |
if usage_post > 4e9 and "readIDs" in df: logging.info("DataFrame of features is too big, dropping read identifiers.") return df.drop(["readIDs"], axis=1, errors="ignore") else: return df |
def check_existance(f): """Check if the file supplied as input exists.""" if not opath.isfile(f): logging.error("Nanoget: File provided doesn't exist or the path is incorrect: {}".format(f)) sys.exit("File provided doesn't exist or the path is incorrect: {}".format(f)) |
def list_user_roles(self): """ Lists user roles as selectable except user's current role. """ _form = JsonForm(current=self.current, title=_(u"Switch Role")) _form.help_text = "Your current role: %s %s" % (self.current.role.unit.name, self.current.role.abstract_role.name) switch_roles = self.get_user_switchable_roles()... |
def change_user_role(self): """ Changes user's role from current role to chosen role. """ # Get chosen role_key from user form. role_key = self.input['form']['role_options'] # Assign chosen switch role key to user's last_login_role_key field self.current.user.last_login_role_key = role_key self.current.user.save() auth... |
def get_user_switchable_roles(self): """ Returns user's role list except current role as a tuple (role.key, role.name) Returns: (list): list of tuples, user's role list except current role """ roles = [] for rs in self.current.user.role_set: # rs.role != self.current.role is not True after python version 2.7.12 if rs.r... |
def put_object(self, obj): # TODO consider putting into a ES class self.pr_dbg('put_obj: %s' % self.json_dumps(obj)) """ Wrapper for es.index, determines metadata needed to index from obj. If you have a raw object json string you can hard code these: index is .kibana (as of kibana4); id can be A-Za-z0-9\- and must be u... |
or index-pattern. """ if obj['_index'] is None or obj['_index'] == "": raise Exception("Invalid Object, no index") if obj['_id'] is None or obj['_id'] == "": raise Exception("Invalid Object, no _id") if obj['_type'] is None or obj['_type'] == "": raise Exception("Invalid Object, no _type") if obj['_source'] is None or ... |
doc_type=obj['_type'], body=obj['_source'], timeout="2m") except RequestError as e: self.pr_err('RequestError: %s, info: %s' % (e.error, e.info)) raise return resp |
def del_object(self, obj): """Debug deletes obj of obj[_type] with id of obj['_id']""" if obj['_index'] is None or obj['_index'] == "": raise Exception("Invalid Object") if obj['_id'] is None or obj['_id'] == "": raise Exception("Invalid Object") if obj['_type'] is None or obj['_type'] == "": raise Exception("Invalid O... |
def json_dumps(self, obj): """Serializer for consistency""" return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) |
def safe_filename(self, otype, oid): """Santize obj name into fname and verify doesn't already exist""" permitted = set(['_', '-', '(', ')']) oid = ''.join([c for c in oid if c.isalnum() or c in permitted]) while oid.find('--') != -1: oid = oid.replace('--', '-') ext = 'json' ts = datetime.now().strftime("%Y%m%dT%H%M%S... |
ext)) fname = '%s-%s-%s.%s' % (otype, oid[:oid_len], ts, ext) is_new = True if os.path.exists(fname): is_new = False ts += '-bck' return fname |
def write_object_to_file(self, obj, path='.', filename=None): """Convert obj (dict) to json string and write to file""" output = self.json_dumps(obj) + '\n' if filename is None: filename = self.safe_filename(obj['_type'], obj['_id']) filename = os.path.join(path, filename) self.pr_inf("Writing to file: " + filename) wi... |
def write_pkg_to_file(self, name, objects, path='.', filename=None): """Write a list of related objs to file""" # Kibana uses an array of docs, do the same # as opposed to a dict of docs pkg_objs = [] for _, obj in iteritems(objects): pkg_objs.append(obj) sorted_pkg = sorted(pkg_objs, key=lambda k: k['_id']) output = s... |
self.pr_inf("Writing to file: " + filename) with open(filename, 'w') as f: f.write(output) return filename |
def get_objects(self, search_field, search_val): """Return all objects of type (assumes < MAX_HITS)""" query = ("{ size: " + str(self.max_hits) + ", " + "query: { filtered: { filter: { " + search_field + ": { value: \"" + search_val + "\"" + " } } } } } }") self.connect_es() res = self.es.search(index=self.index, body=... |
in res['hits']['hits']: objects[doc['_id']] = {} # To make uploading easier in the future: # Record all those bits into the backup. # Mimics how ES returns the result. # Prevents having to store this in some external, contrived, format objects[doc['_id']]['_index'] = self.index # also in doc['_index'] objects[doc['_id'... |
def get_dashboard_full(self, db_name): """Get DB and all objs needed to duplicate it""" objects = {} dashboards = self.get_objects("type", "dashboard") vizs = self.get_objects("type", "visualization") searches = self.get_objects("type", "search") if db_name not in dashboards: return None self.pr_inf("Found dashboard: "... |
" + pid) objects[pid] = searches[pid] elif pid in vizs: self.pr_inf("Found vis: " + pid) objects[pid] = vizs[pid] emb = vizs[pid].get('_source', {}).get('savedSearchId', None) if emb is not None and emb not in objects: if emb not in searches: self.pr_err('Missing search %s' % emb) return objects objects[emb] = searches... |
def parse_node(self, node): """ Overrides ProcessParser.parse_node Parses and attaches the inputOutput tags that created by Camunda Modeller Args: node: xml task node Returns: TaskSpec """ spec = super(CamundaProcessParser, self).parse_node(node) spec.data = self._parse_input_data(node) spec.data['lane_data'] = self._g... |
def _get_description(self): """ Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns: """ ns = {'ns': '{%s}' % BPMN_MODEL_NS} desc = ( self.doc_xpath('.//{ns}collaboration/{ns}documentation'.format(**ns)) or self.doc_xpath('.//{ns}process/{ns}documentation'.format(**ns)) or self.doc_xp... |
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ ns = {'ns': '{%s}' % BPMN_MODEL_NS} for path in ('.//{ns}process', './/{ns}collaboration', './/{ns}collaboration/{ns}participant/'): tag = self.doc_xpath(path.format(**ns)) if tag: name = tag[0].ge... |
def _parse_input_data(self, node): """ Parses inputOutput part camunda modeller extensions. Args: node: SpiffWorkflow Node object. Returns: Data dict. """ data = DotDict() try: for nod in self._get_input_nodes(node): data.update(self._parse_input_node(nod)) except Exception as e: log.exception("Error while processing n... |
def _get_lane_properties(self, node): """ Parses the given XML node Args: node (xml): XML node. .. code-block:: xml <bpmn2:lane id="Lane_8" name="Lane 8"> <bpmn2:extensionElements> <camunda:properties> <camunda:property value="foo,bar" name="perms"/> </camunda:properties> </bpmn2:extensionElements> </bpmn2:lane> Return... |
def _parse_input_node(cls, node): """ :param node: xml node :return: dict """ data = {} child = node.getchildren() if not child and node.get('name'): val = node.text elif child: # if tag = "{http://activiti.org/bpmn}script" then data_typ = 'script' data_typ = child[0].tag.split('}')[1] val = getattr(cls, '_parse_%s' % ... |
def package_in_memory(cls, workflow_name, workflow_files): """ Generates wf packages from workflow diagrams. Args: workflow_name: Name of wf workflow_files: Diagram file. Returns: Workflow package (file like) object """ s = StringIO() p = cls(s, workflow_name, meta_data=[]) p.add_bpmn_files_by_glob(workflow_files) p.cr... |
def compose(self, data): """ condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer """ g = self.__separate(data) if self.__cgr_type in (1, 2, 3, 4, 5, 6) else self.__condense(data) g.meta.update(data.meta) return g |
def add_atom(self, atom, _map=None): """ new atom addition """ if _map is None: _map = max(self, default=0) + 1 elif _map in self._node: raise KeyError('atom with same number exists') attr_dict = self.node_attr_dict_factory() if isinstance(atom, str): attr_dict.element = atom elif isinstance(atom, int): attr_dict.eleme... |
def add_bond(self, atom1, atom2, bond): """ implementation of bond addition """ if atom1 == atom2: raise KeyError('atom loops impossible') if atom1 not in self._node or atom2 not in self._node: raise KeyError('atoms not found') if atom1 in self._adj[atom2]: raise KeyError('atoms already bonded') attr_dict = self.edge_a... |
def delete_bond(self, n, m): """ implementation of bond removing """ self.remove_edge(n, m) self.flush_cache() |
def environment(self, atom): """ pairs of (bond, atom) connected to atom :param atom: number :return: list """ return tuple((bond, self._node[n]) for n, bond in self._adj[atom].items()) |
def substructure(self, atoms, meta=False, as_view=True): """ create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view provides a read-only view of the original s... |
s.delete_bond = frozen # more informative exception return s s = s.copy() if not meta: s.graph.clear() return s |
def augmented_substructure(self, atoms, dante=False, deep=1, meta=False, as_view=True): """ create substructure containing atoms and their neighbors :param atoms: list of core atoms in graph :param dante: if True return list of graphs containing atoms, atoms + first circle, atoms + 1st + 2nd, etc up to deep or while ne... |
to each substructure :param as_view: If True, the returned graph-view provides a read-only view of the original graph without actually copying any data """ nodes = [set(atoms)] for i in range(deep): n = {y for x in nodes[-1] for y in self._adj[x]} | nodes[-1] if n in nodes: break nodes.append(n) if dante: return [self.... |
as_view) |
def split(self, meta=False): """ split disconnected structure to connected substructures :param meta: copy metadata to each substructure :return: list of substructures """ return [self.substructure(c, meta, False) for c in connected_components(self)] |
def bonds(self): """ iterate other all bonds """ seen = set() for n, m_bond in self._adj.items(): seen.add(n) for m, bond in m_bond.items(): if m not in seen: yield n, m, bond |
def _get_subclass(name): """ need for cyclic import solving """ return next(x for x in BaseContainer.__subclasses__() if x.__name__ == name) |
def _default_make_pool(http, proxy_info): """Creates a urllib3.PoolManager object that has SSL verification enabled and uses the certifi certificates.""" if not http.ca_certs: http.ca_certs = _certifi_where_for_ssl_version() ssl_disabled = http.disable_ssl_certificate_validation cert_reqs = 'CERT_REQUIRED' if http.ca_c... |
else: proxy_url = 'http://{}:{}/'.format( proxy_info.proxy_host, proxy_info.proxy_port, ) proxy_headers = {} return urllib3.ProxyManager( proxy_url=proxy_url, proxy_headers=proxy_headers, ca_certs=http.ca_certs, cert_reqs=cert_reqs, ) return urllib3.PoolManager( ca_certs=http.ca_certs, cert_reqs=cert_reqs, ) |
def patch(make_pool=_default_make_pool): """Monkey-patches httplib2.Http to be httplib2shim.Http. This effectively makes all clients of httplib2 use urlilb3. It's preferable to specify httplib2shim.Http explicitly where you can, but this can be useful in situations where you do not control the construction of the http ... |
needed. By default, this will create a urllib3.PoolManager with SSL verification enabled using the certifi certificates. """ setattr(httplib2, '_HttpOriginal', httplib2.Http) httplib2.Http = Http Http._make_pool = make_pool |
def _is_ipv6(addr): """Checks if a given address is an IPv6 address.""" try: socket.inet_pton(socket.AF_INET6, addr) return True except socket.error: return False |
def _certifi_where_for_ssl_version(): """Gets the right location for certifi certifications for the current SSL version. Older versions of SSL don't support the stronger set of root certificates. """ if not ssl: return if ssl.OPENSSL_VERSION_INFO < (1, 0, 2): warnings.warn( 'You are using an outdated version of OpenSSL... |
def _map_response(response, decode=False): """Maps a urllib3 response to a httplib/httplib2 Response.""" # This causes weird deepcopy errors, so it's commented out for now. # item._urllib3_response = response item = httplib2.Response(response.getheaders()) item.status = response.status item['status'] = str(item.status)... |
# This does not occur for 'HEAD' requests. if decode and item.get('content-encoding') in ['gzip', 'deflate']: item['content-length'] = str(len(response.data)) item['-content-encoding'] = item.pop('content-encoding') return item |
def _map_exception(e): """Maps an exception from urlib3 to httplib2.""" if isinstance(e, urllib3.exceptions.MaxRetryError): if not e.reason: return e e = e.reason message = e.args[0] if e.args else '' if isinstance(e, urllib3.exceptions.ResponseError): if 'too many redirects' in message: return httplib2.RedirectLimit(m... |
hostname.') if 'Connection refused' in message: return socket.error((errno.ECONNREFUSED, 'Connection refused')) if isinstance(e, urllib3.exceptions.DecodeError): return httplib2.FailedToDecompressContent( 'Content purported as compressed but not uncompressable.', httplib2.Response({'status': 500}), '') if isinstance(e,... |
def run_workers(no_subprocess, watch_paths=None, is_background=False): """ subprocess handler """ import atexit, os, subprocess, signal if watch_paths: from watchdog.observers import Observer # from watchdog.observers.fsevents import FSEventsObserver as Observer # from watchdog.observers.polling import PollingObserver ... |
= FileSystemEventHandler() handler.on_modified = on_modified # global child_pids child_pids = [] log.info("starting %s workers" % no_subprocess) def run_children(): global child_pids child_pids = [] for i in range(int(no_subprocess)): proc = subprocess.Popen([sys.executable, __file__], stdout=subprocess.PIPE, stderr=su... |
os.kill(pid, signal.SIGTERM) run_children() atexit.register(kill_children) signal.signal(signal.SIGTERM, kill_children) if watch_paths: observer = Observer() for path in watch_paths: if not is_background: print("Watching for changes under %s" % path) observer.schedule(handler, path=path, recursive=True) observer.start(... |
def exit(self, signal=None, frame=None): """ Properly close the AMQP connections """ self.input_channel.close() self.client_queue.close() self.connection.close() log.info("Worker exiting") sys.exit(0) |
def connect(self): """ make amqp connection and create channels and queue binding """ self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS) self.client_queue = ClientQueue() self.input_channel = self.connection.channel() self.input_channel.exchange_declare(exchange=self.INPUT_EXCHANGE, type='topic', durable=Tru... |
def clear_queue(self): """ clear outs all messages from INPUT_QUEUE_NAME """ def remove_message(ch, method, properties, body): print("Removed message: %s" % body) self.input_channel.basic_consume(remove_message, queue=self.INPUT_QUEUE_NAME, no_ack=True) try: self.input_channel.start_consuming() except (KeyboardInterrup... |
def run(self): """ actual consuming of incoming works starts here """ self.input_channel.basic_consume(self.handle_message, queue=self.INPUT_QUEUE_NAME, no_ack=True ) try: self.input_channel.start_consuming() except (KeyboardInterrupt, SystemExit): log.info(" Exiting") self.exit() |
def handle_message(self, ch, method, properties, body): """ this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body """ input = {} headers = {} try: self.sessid = method.routing_key input = json_decode(b... |
TODO: just a workaround till we modify ui to if 'path' in data: if data['path'] in VIEW_METHODS: data['view'] = data['path'] else: data['wf'] = data['path'] session = Session(self.sessid) headers = {'remote_ip': input['_zops_remote_ip'], 'source': input['_zops_source']} if 'wf' in data: output = self._handle_workflow(s... |
'_called_from_test'): raise output = {"cmd": "error", "error": self._prepare_error_msg(e.message), "code": e.code} log.exception("Http error occurred") except: self.current = Current(session=session, input=data) self.current.headers = headers import sys if hasattr(sys, '_called_from_test'): raise err = traceback.format... |
def get_progress(start, finish): """ Args: start (DateTime): start date finish (DateTime): finish date Returns: """ now = datetime.now() dif_time_start = start - now dif_time_finish = finish - now if dif_time_start.days < 0 and dif_time_finish.days < 0: return PROGRESS_STATES[3][0] elif dif_time_start.days < 0 and dif_... |
def sync_wf_cache(current): """ BG Job for storing wf state to DB """ wf_cache = WFCache(current) wf_state = wf_cache.get() # unicode serialized json to dict, all values are unicode if 'role_id' in wf_state: # role_id inserted by engine, so it's a sign that we get it from cache not db try: wfi = WFInstance.objects.get(... |
wfi = WFInstance(key=current.input['token']) wfi.wf = BPMNWorkflow.objects.get(name=wf_state['name']) if not wfi.current_actor.exist: # we just started the wf try: inv = TaskInvitation.objects.get(instance=wfi, role_id=wf_state['role_id']) inv.delete_other_invitations() inv.progress = 20 inv.save() except ObjectDoesNot... |
wf_state['finished']: wfi.finished = True wfi.finish_date = wf_state['finish_date'] wf_cache.delete() wfi.save() else: # if cache already cleared, we have nothing to sync pass |
def get_or_create_by_content(cls, name, content): """ if xml content updated, create a new entry for given wf name Args: name: name of wf content: xml content Returns (DiagramXML(), bool): A tuple with two members. (DiagramXML instance and True if it's new or False it's already exists """ new = False diagrams = cls.obj... |
else: new = True if new: diagram = cls(name=name, body=content).save() return diagram, new |
def get_description(self): """ Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns str: WF description """ paths = ['bpmn:collaboration/bpmn:participant/bpmn:documentation', 'bpmn:collaboration/bpmn:documentation', 'bpmn:process/bpmn:documentation'] for path in paths: elm = self.root.... |
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ paths = ['bpmn:process', 'bpmn:collaboration/bpmn:participant/', 'bpmn:collaboration', ] for path in paths: tag = self.root.find(path, NS) if tag is not None and len(tag): name = tag.get('name') if... |
def set_xml(self, diagram, force=False): """ updates xml link if there aren't any running instances of this wf Args: diagram: XMLDiagram object """ no_of_running = WFInstance.objects.filter(wf=self, finished=False, started=True).count() if no_of_running and not force: raise RunningInstancesExist( "Can't update WF diagr... |
self.name.replace('_', ' ').title() extensions = dict(parser.get_wf_extensions()) self.programmable = extensions.get('programmable', False) self.task_type = extensions.get('task_type', None) self.menu_category = extensions.get('menu_category', settings.DEFAULT_WF_CATEGORY_NAME) self.save() |
def create_wf_instances(self, roles=None): """ Creates wf instances. Args: roles (list): role list Returns: (list): wf instances """ # if roles specified then create an instance for each role # else create only one instance if roles: wf_instances = [ WFInstance( wf=self.wf, current_actor=role, task=self, name=self.wf.n... |
is not related with objects save instances immediately. if self.task_type in ["C", "D"]: return [wfi.save() for wfi in wf_instances] # if task type is related with its objects, save populate instances per object else: wf_obj_instances = [] for wfi in wf_instances: role = wfi.current_actor if self.task_type == "A" else ... |
in keys] ) return wf_obj_instances |
def create_tasks(self): """ will create a WFInstance per object and per TaskInvitation for each role and WFInstance """ roles = self.get_roles() if self.task_type in ["A", "D"]: instances = self.create_wf_instances(roles=roles) self.create_task_invitation(instances) elif self.task_type in ["C", "B"]: instances = self.c... |
def get_object_query_dict(self): """returns objects keys according to self.object_query_code which can be json encoded queryset filter dict or key=value set in the following format: ```"key=val, key2 = val2 , key3= value with spaces"``` Returns: (dict): Queryset filtering dicqt """ if isinstance(self.object_query_code,... |
key3= value with spaces" return dict(pair.split('=') for pair in self.object_query_code.split(',')) |
def get_object_keys(self, wfi_role=None): """returns object keys according to task definition which can be explicitly selected one object (self.object_key) or result of a queryset filter. Returns: list of object keys """ if self.object_key: return [self.object_key] if self.object_query_code: model = model_registry.get_... |
def get_model_objects(model, wfi_role=None, **kwargs): """ Fetches model objects by filtering with kwargs If wfi_role is specified, then we expect kwargs contains a filter value starting with role, e.g. {'user': 'role.program.user'} We replace this `role` key with role instance parameter `wfi_role` and try to get objec... |
Model class wfi_role (Role): role instance of wf instance **kwargs: filter arguments Returns: (list): list of model object instances """ query_dict = {} for k, v in kwargs.items(): if isinstance(v, list): query_dict[k] = [str(x) for x in v] else: parse = str(v).split('.') if parse[0] == 'role' and wfi_role: query_dict[... |
model.objects.all(**query_dict) |
def get_roles(self): """ Returns: Role instances according to task definition. """ if self.role.exist: # return explicitly selected role return [self.role] else: roles = [] if self.role_query_code: # use given "role_query_code" roles = RoleModel.objects.filter(**self.role_query_code) elif self.unit.exist: # get roles f... |
in UnitModel.get_role_keys(self.unit.key)) else: roles = RoleModel.objects.filter(unit=self.unit) elif self.get_roles_from: # get roles from selected predefined "get_roles_from" method return ROLE_GETTER_METHODS[self.get_roles_from](RoleModel) if self.abstract_role.exist and roles: # apply abstract_role filtering on ro... |
def post_save(self): """can be removed when a proper task manager admin interface implemented""" if self.run: self.run = False self.create_tasks() self.save() |
def delete_other_invitations(self): """ When one person use an invitation, we should delete other invitations """ # TODO: Signal logged-in users to remove the task from their task list self.objects.filter(instance=self.instance).exclude(key=self.key).delete() |
def save(self, wf_state): """ write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache Args: wf_state dict: wf state """ self.wf_state = wf_state self.wf_state['role_id'] = self.current.role_id self.set(self.wf_state) if self.wf_state['name'] not in settings.EPHEMERAL_WORKFLOWS: self.publish(job='_zops_sync_wf_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.