text
stringlengths
18
773k
def isNodeAuthorizedResponse(self, targetNodeSubject, pid, vendorSpecific=None): """CNReplication.isNodeAuthorized(session, targetNodeSubject, pid, replicatePermission) → boolean() https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNReplication.isNodeAuthorized. ...
def isNodeAuthorized(self, targetNodeSubject, pid, vendorSpecific=None): """See Also: isNodeAuthorizedResponse() Args: targetNodeSubject: pid: vendorSpecific: Returns: """ response = self.isNodeAuthorizedResponse(targetNodeSubject, pid, vendorSpec...
def deleteReplicationMetadataResponse( self, pid, nodeId, serialVersion, vendorSpecific=None ): """CNReplication.deleteReplicationMetadata(session, pid, policy, serialVersion) → boolean https://releases.dataone.org/online/api-docume ntation-v2.0.1/apis/CN_APIs.html#CNReplication.del...
def deleteReplicationMetadata( self, pid, nodeId, serialVersion, vendorSpecific=None ): """See Also: deleteReplicationMetadataResponse() Args: pid: nodeId: serialVersion: vendorSpecific: Returns: """ response = self.deleteRep...
def updateNodeCapabilitiesResponse(self, nodeId, node, vendorSpecific=None): """CNRegister.updateNodeCapabilities(session, nodeId, node) → boolean https://releases.dataone.org/online/api-documentation-v2.0.1/apis/CN_AP Is.html#CNRegister.updateNodeCapabilities. Args: nodeId: ...
def updateNodeCapabilities(self, nodeId, node, vendorSpecific=None): """See Also: updateNodeCapabilitiesResponse() Args: nodeId: node: vendorSpecific: Returns: """ response = self.updateNodeCapabilitiesResponse(nodeId, node, vendorSpecific) ...
def registerResponse(self, node, vendorSpecific=None): """CNRegister.register(session, node) → NodeReference https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNRegister.register. Args: node: vendorSpecific: Returns: ""...
def register(self, node, vendorSpecific=None): """See Also: registerResponse() Args: node: vendorSpecific: Returns: """ response = self.registerResponse(node, vendorSpecific) return self._read_boolean_response(response)
def valid(self, instance, schema): """Validate schema.""" try: jsonschema.validate(instance, schema) except jsonschema.exceptions.ValidationError as ex: self.stderr.write(" VALIDATION ERROR: {}".format(instance['name'] if 'name' in instance else '')) self.s...
def find_descriptor_schemas(self, schema_file): """Find descriptor schemas in given path.""" if not schema_file.lower().endswith(('.yml', '.yaml')): return [] with open(schema_file) as fn: schemas = yaml.load(fn, Loader=yaml.FullLoader) if not schemas: ...
def find_schemas(self, schema_path, schema_type=SCHEMA_TYPE_PROCESS, verbosity=1): """Find schemas in packages that match filters.""" schema_matches = [] if not os.path.isdir(schema_path): if verbosity > 0: self.stdout.write("Invalid path {}".format(schema_path)) ...
def register_processes(self, process_schemas, user, force=False, verbosity=1): """Read and register processors.""" log_processors = [] log_templates = [] for p in process_schemas: # TODO: Remove this when all processes are migrated to the # new syntax. ...
def register_descriptors(self, descriptor_schemas, user, force=False, verbosity=1): """Read and register descriptors.""" log_descriptors = [] for descriptor_schema in descriptor_schemas: for schema, _, _ in iterate_schema({}, descriptor_schema.get('schema', {})): if ...
def retire(self, process_schemas): """Retire obsolete processes. Remove old process versions without data. Find processes that have been registered but do not exist in the code anymore, then: - If they do not have data: remove them - If they have data: flag them not active (``i...
def handle(self, *args, **options): """Register processes.""" force = options.get('force') retire = options.get('retire') verbosity = int(options.get('verbosity')) users = get_user_model().objects.filter(is_superuser=True).order_by('date_joined') if not users.exists(): ...
def is_valid_pid_for_create(did): """Return True if ``did`` is the PID of an object that can be created with MNStorage.create() or MNStorage.update(). To be valid for create() and update(), the DID: - Must not be the PID of an object that exists on this MN - Must not be a known SID known to this M...
def is_valid_pid_to_be_updated(did): """Return True if ``did`` is the PID of an object that can be updated (obsoleted) with MNStorage.update()""" return ( is_existing_object(did) and not is_local_replica(did) and not is_archived(did) and not is_obsoleted(did) )
def is_valid_sid_for_chain(pid, sid): """Return True if ``sid`` can be assigned to the single object ``pid`` or to the chain to which ``pid`` belongs. - If the chain does not have a SID, the new SID must be previously unused. - If the chain already has a SID, the new SID must match the existing SID. ...
def is_existing_object(did): """Return True if PID is for an object for which science bytes are stored locally. This excludes SIDs and PIDs for unprocessed replica requests, remote or non-existing revisions of local replicas and objects aggregated in Resource Maps. """ return d1_gmn.app.models.Sci...
def classify_identifier(did): """Return a text fragment classifying the ``did`` Return <UNKNOWN> if the DID could not be classified. This should not normally happen and may indicate that the DID was orphaned in the database. """ if _is_unused_did(did): return 'unused on this Member Node' ...
def is_local_replica(pid): """Includes unprocessed replication requests.""" return d1_gmn.app.models.LocalReplica.objects.filter(pid__did=pid).exists()
def is_unprocessed_local_replica(pid): """Is local replica with status "queued".""" return d1_gmn.app.models.LocalReplica.objects.filter( pid__did=pid, info__status__status='queued' ).exists()
def is_revision_chain_placeholder(pid): """For replicas, the PIDs referenced in revision chains are reserved for use by other replicas.""" return d1_gmn.app.models.ReplicaRevisionChainReference.objects.filter( pid__did=pid ).exists()
def _is_did(did): """Return True if ``did`` is recorded in a local context. ``did``=None is supported and returns False. A DID can be classified with classify_identifier(). """ return d1_gmn.app.models.IdNamespace.objects.filter(did=did).exists()
def prepare_connection(): """Set dafault connection for ElasticSearch. .. warning:: In case of using multiprocessing/multithreading, connection will be probably initialized in the main process/thread and the same connection (socket) will be used in all processes/threads. This w...
def _log(pid, request, event, timestamp=None): """Log an operation that was performed on a sciobj.""" # Support logging events that are not associated with an object. sciobj_model = None if pid is not None: try: sciobj_model = d1_gmn.app.models.ScienceObject.objects.filter(pid__did=p...
def _is_ignored_read_event(request): """Return True if this read event was generated by an automated process, as indicated by the user configurable LOG_IGNORE* settings. See settings_site.py for description and rationale for the settings. """ if ( django.conf.settings.LOG_IGNORE_TRUSTED_SU...
def action_to_level(action): """Map action name to action level.""" try: return ACTION_LEVEL_MAP[action] except LookupError: raise d1_common.types.exceptions.InvalidRequest( 0, 'Unknown action. action="{}"'.format(action) )
def level_to_action(level): """Map action level to action name.""" try: return LEVEL_ACTION_MAP[level] except LookupError: raise d1_common.types.exceptions.InvalidRequest( 0, 'Unknown action level. level="{}"'.format(level) )
def get_trusted_subjects(): """Get set of subjects that have unlimited access to all SciObj and APIs on this node.""" cert_subj = _get_client_side_certificate_subject() return ( d1_gmn.app.node_registry.get_cn_subjects() | django.conf.settings.DATAONE_TRUSTED_SUBJECTS | {cert_sub...
def is_trusted_subject(request): """Determine if calling subject is fully trusted.""" logging.debug('Active subjects: {}'.format(', '.join(request.all_subjects_set))) logging.debug('Trusted subjects: {}'.format(', '.join(get_trusted_subjects()))) return not request.all_subjects_set.isdisjoint(get_truste...
def _get_client_side_certificate_subject(): """Return the DN from the client side certificate as a D1 subject if a client side cert has been configured. Else return None. """ subject = django.core.cache.cache.get('client_side_certificate_subject') if subject is not None: return subject...
def is_allowed(request, level, pid): """Check if one or more subjects are allowed to perform action level on object. If a subject holds permissions for one action level on object, all lower action levels are also allowed. Any included subject that is unknown to this MN is treated as a subject without p...
def assert_create_update_delete_permission(request): """Access only by subjects with Create/Update/Delete permission and by trusted infrastructure (CNs).""" if not has_create_update_delete_permission(request): raise d1_common.types.exceptions.NotAuthorized( 0, 'Access allowed...
def assert_allowed(request, level, pid): """Assert that one or more subjects are allowed to perform action on object. Raise NotAuthorized if object exists and subject is not allowed. Raise NotFound if object does not exist. """ if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).ex...
def format_active_subjects(request): """Create a string listing active subjects for this connection, suitable for appending to authentication error messages.""" decorated_subject_list = [request.primary_subject_str + ' (primary)'] for subject in request.all_subjects_set: if subject != request.pr...
def main(): """Remove unused imports Unsafe! Only tested on our codebase, which uses simple absolute imports on the form, "import a.b.c". """ parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", na...
def comment_import(r, unused_dot_list): """Comment out import for {dot_str}.""" unused_dot_str = ".".join(unused_dot_list) for n in r("ImportNode"): if n.names()[0] == unused_dot_str: # The "!" is inserted so that this line doesn't show up when searching for # the comment pat...
def get_atomtrailer_list(r): """Capture only the leading dotted name list. A full sequence typically includes function calls and parameters. pkga.pkgb.pkgc.one_call(arg1, arg2, arg3=4) """ dot_set = set() for n in r.find_all(("atomtrailers",)): name_list = [] for x in n.value: ...
def custom_filter_tags(self, value, search): """Support tags query.""" if not isinstance(value, list): value = value.split(',') filters = [Q('match', **{'tags': item}) for item in value] search = search.query('bool', must=filters) return search
def custom_filter_text(self, value, search): """Support general query using the 'text' attribute.""" if isinstance(value, list): value = ' '.join(value) should = [ Q('match', slug={'query': value, 'operator': 'and', 'boost': 10.0}), Q('match', **{'slug.ngrams...
def set_content_permissions(self, user, obj, payload): """Apply permissions to data objects and entities in ``Collection``.""" for entity in obj.entity_set.all(): if user.has_perm('share_entity', entity): update_permission(entity, payload) # Data doesn't have "ADD" p...
def create(self, request, *args, **kwargs): """Only authenticated usesr can create new collections.""" if not request.user.is_authenticated: raise exceptions.NotFound return super().create(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs): """Destroy a model instance. If ``delete_content`` flag is set in query parameters, also all Data objects and Entities, on which user has ``EDIT`` permission, contained in collection will be deleted. """ obj = self.get_object(...
def add_data(self, request, pk=None): """Add data to collection.""" collection = self.get_object() if 'ids' not in request.data: return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST) missing = [] for data_id in request.data['id...
def remove_data(self, request, pk=None): """Remove data from collection.""" collection = self.get_object() if 'ids' not in request.data: return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST) for data_id in request.data['ids']: ...
def duplicate(self, request, *args, **kwargs): """Duplicate (make copy of) ``Collection`` models.""" if not request.user.is_authenticated: raise exceptions.NotFound ids = self.get_ids(request.data) queryset = get_objects_for_user(request.user, 'view_collection', Collection.o...
async def is_object_synced_to_cn(self, client, pid): """Check if object with {pid} has successfully synced to the CN. CNRead.describe() is used as it's a light-weight HTTP HEAD request. This assumes that the call is being made over a connection that has been authenticated and has read ...
def apply(self, search, field, value): """Apply lookup expression to search query.""" return search.query( self.query_type( # pylint: disable=not-callable **{ field: { self.operator: self.get_value_query(value) ...
def apply(self, search, field, value): """Apply lookup expression to search query.""" if not isinstance(value, list): value = [x for x in value.strip().split(',') if x] filters = [Q('match', **{field: item}) for item in value] return search.query('bool', should=filters)
def apply(self, search, field, value): """Apply lookup expression to search query.""" # We assume that the field in question has a "raw" counterpart. return search.query('match', **{'{}.raw'.format(field): value})
def register_lookup(self, lookup): """Register lookup.""" if lookup.operator in self._lookups: raise KeyError("Lookup for operator '{}' is already registered".format(lookup.operator)) self._lookups[lookup.operator] = lookup()
def get_lookup(self, operator): """Look up a lookup. :param operator: Name of the lookup operator """ try: return self._lookups[operator] except KeyError: raise NotImplementedError("Lookup operator '{}' is not supported".format(operator))
def build(self, search, raw_query): """Build query. :param search: Search query instance :param raw_query: Raw query arguments dictionary """ unmatched_items = {} for expression, value in raw_query.items(): # Parse query expression into tokens. to...
def resolve_sid(f): """View handler decorator that adds SID resolve and PID validation. - For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's not valid. - For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as a SID and, if successful, return th...
def decode_did(f): """View handler decorator that decodes "%2f" ("/") in SID or PID extracted from URL path segment by Django.""" @functools.wraps(f) def wrapper(request, did, *args, **kwargs): return f(request, decode_path_segment(did), *args, **kwargs) return wrapper
def trusted_permission(f): """Access only by D1 infrastructure.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): trusted(request) return f(request, *args, **kwargs) return wrapper
def list_objects_access(f): """Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): if not django.conf.settings.PUBLIC_OBJECT_LIST: trusted(request) return f(request, *args, **kwargs) return wrapper
def get_log_records_access(f): """Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): if not django.conf.settings.PUBLIC_LOG_RECORDS: trusted(request) return f(request, *args, **kwargs) return wr...
def assert_create_update_delete_permission(f): """Access only by subjects with Create/Update/Delete permission and by trusted infrastructure (CNs).""" @functools.wraps(f) def wrapper(request, *args, **kwargs): d1_gmn.app.auth.assert_create_update_delete_permission(request) return f(requ...
def authenticated(f): """Access only with a valid session.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): if d1_common.const.SUBJECT_AUTHENTICATED not in request.all_subjects_set: raise d1_common.types.exceptions.NotAuthorized( 0, 'Access a...
def required_permission(f, level): """Assert that subject has access at given level or higher for object.""" @functools.wraps(f) def wrapper(request, pid, *args, **kwargs): d1_gmn.app.auth.assert_allowed(request, level, pid) return f(request, pid, *args, **kwargs) return wrapper
def _read_and_deserialize_dataone_type(self, response): """Given a response body, try to create an instance of a DataONE type. The return value will be either an instance of a type or a DataONE exception. """ try: return d1_common.xml.deserialize(response.content) e...
def get(self, pid, stream=False, vendorSpecific=None): """Initiate a MNRead.get(). Return a Requests Response object from which the object bytes can be retrieved. When ``stream`` is False, Requests buffers the entire object in memory before returning the Response. This can exhaust avail...
def get_and_save( self, pid, sciobj_stream, create_missing_dirs=False, vendorSpecific=None ): """Like MNRead.get(), but also retrieve the object bytes and store them in a stream. This method does not have the potential issue with excessive memory usage that get() with ``stream``=Fals...
def describe(self, pid, vendorSpecific=None): """Note: If the server returns a status code other than 200 OK, a ServiceFailure will be raised, as this method is based on a HEAD request, which cannot carry exception information.""" response = self.describeResponse(pid, vendorSpecific=vend...
def isAuthorized(self, pid, action, vendorSpecific=None): """Return True if user is allowed to perform ``action`` on ``pid``, else False.""" response = self.isAuthorizedResponse(pid, action, vendorSpecific) return self._read_boolean_401_response(response)
def fields(self): """Filter fields based on request query parameters.""" fields = super().fields return apply_subfield_projection(self, copy.copy(fields))
def iterate_fields(fields, schema, path_prefix=None): """Iterate over all field values sub-fields. This will iterate over all field values. Some fields defined in the schema might not be visited. :param fields: field values to iterate over :type fields: dict :param schema: schema to iterate ov...
def iterate_schema(fields, schema, path_prefix=''): """Iterate over all schema sub-fields. This will iterate over all field definitions in the schema. Some field v alues might be None. :param fields: field values to iterate over :type fields: dict :param schema: schema to iterate over :typ...
def iterate_dict(container, exclude=None, path=None): """Iterate over a nested dictionary. The dictionary is iterated over in a depth first manner. :param container: Dictionary to iterate over :param exclude: Optional callable, which is given key and value as arguments and may return True to s...
def get_subjects(request): """Get all subjects in the certificate. - Returns: primary_str (primary subject), equivalent_set (equivalent identities, groups and group memberships) - The primary subject is the certificate subject DN, serialized to a DataONE compliant subject string. """ i...
def get_authenticated_subjects(cert_pem): """Return primary subject and set of equivalents authenticated by certificate. - ``cert_pem`` can be str or bytes """ if isinstance(cert_pem, str): cert_pem = cert_pem.encode('utf-8') return d1_common.cert.subjects.extract_subjects(cert_pem)
def get_serializer_class(self): """Augment base serializer class. Include permissions information with objects. """ base_class = super().get_serializer_class() class SerializerWithPermissions(base_class): """Augment serializer class.""" def get_fields(...
def detail_permissions(self, request, pk=None): """Get or set permissions API endpoint.""" obj = self.get_object() if request.method == 'POST': content_type = ContentType.objects.get_for_model(obj) payload = request.data share_content = strtobool(payload.pop(...
def save(self, *args, **kwargs): """Perform descriptor validation and save object.""" if self.descriptor_schema: try: validate_schema(self.descriptor, self.descriptor_schema.schema) # pylint: disable=no-member self.descriptor_dirty = False except ...
def duplicate(self, contributor=None): """Duplicate (make a copy).""" duplicate = Collection.objects.get(id=self.id) duplicate.pk = None duplicate.slug = None duplicate.name = 'Copy of {}'.format(self.name) duplicate.duplicated = now() if contributor: ...
def _scalar2array(d): """Convert a dictionary with scalar elements and string indices '_1234' to a dictionary of arrays. Unspecified entries are np.nan.""" da = {} for k, v in d.items(): if '_' not in k: da[k] = v else: name = ''.join(k.split('_')[:-1]) ...
def _symm_herm(C): """To get rid of NaNs produced by _scalar2array, symmetrize operators where C_ijkl = C_jilk*""" nans = np.isnan(C) C[nans] = np.einsum('jilk', C)[nans].conj() return C
def _symm_current(C): """To get rid of NaNs produced by _scalar2array, symmetrize operators where C_ijkl = C_klij""" nans = np.isnan(C) C[nans] = np.einsum('klij', C)[nans] return C
def _antisymm_12(C): """To get rid of NaNs produced by _scalar2array, antisymmetrize the first two indices of operators where C_ijkl = -C_jikl""" nans = np.isnan(C) C[nans] = -np.einsum('jikl', C)[nans] return C
def JMS_to_array(C, sectors=None): """For a dictionary with JMS Wilson coefficients, return a dictionary of arrays.""" if sectors is None: wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs else: try: wc_keys = [k for s in sectors for k in wcxf.Basis['WET', 'JMS'].sectors[s]] ...
def symmetrize_JMS_dict(C): """For a dictionary with JMS Wilson coefficients but keys that might not be in the non-redundant basis, return a dictionary with keys from the basis and values conjugated if necessary.""" wc_keys = set(wcxf.Basis['WET', 'JMS'].all_wcs) Cs = {} for op, v in C.items(): ...
def rotate_down(C_in, p): """Redefinition of all Wilson coefficients in the JMS basis when rotating down-type quark fields from the flavour to the mass basis. C_in is expected to be an array-valued dictionary containg a key for all Wilson coefficient matrices.""" C = C_in.copy() V = ckmutil.ckm...
def scale_dict_wet(C): """To account for the fact that arXiv:Jenkins:2017jig uses a flavour non-redundant basis in contrast to WCxf, symmetry factors of two have to be introduced in several places for operators that are symmetric under the interchange of two currents.""" return {k: v / _scale_dict[k...
def unscale_dict_wet(C): """Undo the scaling applied in `scale_dict_wet`.""" return {k: _scale_dict[k] * v for k, v in C.items()}
def write_reqs(req_path, req_list): """ Args: req_path: req_list: """ with open(req_path, 'w') as f: f.write('\n'.join(req_list) + "\n")
def submit(self, data, runtime_dir, argv): """Run process locally. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ logger.debug(__( "Connector '{}' running for Data with id {} ({}).", self.__class__.__mod...
def create_checksum_object_from_stream( f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of a stream. Args: f: file-like object Only requirement is a ``read()`` method that returns ``bytes``. algorithm: str Checksum algorithm, ``MD5`` or ``SH...
def create_checksum_object_from_iterator( itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of an iterator. Args: itr: iterable Object which supports the iterator protocol. algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. ...
def create_checksum_object_from_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: ...
def calculate_checksum_on_stream( f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM, chunk_size=DEFAULT_CHUNK_SIZE, ): """Calculate the checksum of a stream. Args: f: file-like object Only requirement is a ``read()`` method that returns ``bytes``. algorithm: str C...
def calculate_checksum_on_iterator( itr, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of an iterator. Args: itr: iterable Object which supports the iterator protocol. algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. R...
def calculate_checksum_on_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes ...
def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb): """Determine if checksums are equal. Args: checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare. Returns: bool - **True**: The checksums contain the same hexadecimal values calculated with the same algo...
def format_checksum(checksum_pyxb): """Create string representation of a PyXB Checksum object. Args: PyXB Checksum object Returns: str : Combined hexadecimal value and algorithm name. """ return '{}/{}'.format( checksum_pyxb.algorithm.upper().replace('-', ''), checksum_pyxb.va...
def handle(self, *args, **kwargs): """Run the executor listener. This method never returns.""" listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {})) def _killer(signum, frame): """Kill the listener on receipt of a signal.""" ...
def apply_subfield_projection(field, value, deep=False): """Apply projection from request context. The passed dictionary may be mutated. :param field: An instance of `Field` or `Serializer` :type field: `Field` or `Serializer` :param value: Dictionary to apply the projection to :type value: di...
def apply_projection(projection, value): """Apply projection.""" if isinstance(value, Sequence): # Apply projection to each item in the list. return [ apply_projection(projection, item) for item in value ] elif not isinstance(value, Mapping): # Non-dic...
def _create_partitions(self, instance, partitions): """Create partitions.""" for partition in partitions: RelationPartition.objects.create( relation=instance, entity=partition['entity'], label=partition.get('label', None), posit...