Python uuid.uuid5() Examples

The following are 30 code examples of uuid.uuid5(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module uuid , or try the search function .
Example #1
Source File: test_uuid.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_uuid5(self):
        equal = self.assertEqual

        # Test some known version-5 UUIDs.
        for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
                      '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
                     (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
                      '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
                     (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
                      '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
                     (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
                      'cc957dd1-a972-5349-98cd-874190002798'),
                    ]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 5)
            equal(u, uuid.UUID(v))
            equal(str(u), v) 
Example #2
Source File: detect.py    From hardware with Apache License 2.0 6 votes vote down vote up
def _get_uuid_ppc64le(hw_lst):
    vendor = None
    serial = None
    for (_, _, sys_subtype, value) in hw_lst:
        if sys_subtype == 'vendor':
            vendor = value
        if sys_subtype == 'serial':
            serial = value

    system_uuid = None
    system_uuid_fname = '/sys/firmware/devicetree/base/system-uuid'
    if os.access(system_uuid_fname, os.R_OK):
        with open(system_uuid_fname) as uuidfile:
            system_uuid = uuidfile.read().rstrip(' \t\r\n\0')
    elif vendor and serial:
        root = uuid.UUID(bytes=b'\x00' * 16)
        vendor_uuid = uuid.uuid5(root, vendor)
        system_uuid = str(uuid.uuid5(vendor_uuid, serial))

    return system_uuid 
Example #3
Source File: test_uuid.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_uuid5(self):
        equal = self.assertEqual

        # Test some known version-5 UUIDs.
        for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
                      '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
                     (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
                      '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
                     (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
                      '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
                     (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
                      'cc957dd1-a972-5349-98cd-874190002798'),
                    ]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 5)
            equal(u, uuid.UUID(v))
            equal(str(u), v) 
Example #4
Source File: writer.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 6 votes vote down vote up
def set_relative_to_parent(blender_object, json_data):
    if blender_object.parent:
        parent = blender_object.parent
        
        parent_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, parent.name)
        
        parent_orientation = quat_swap_nzy(relative_rotation(blender_object))
        parent_position = swap_nzy(relative_position(blender_object))
        
        json_data["position"] = {
            'x': parent_position.x,
            'y': parent_position.y,
            'z': parent_position.z
        }
        
        json_data["rotation"] = {
            'x': parent_orientation.x,
            'y': parent_orientation.y,
            'z': parent_orientation.z,
            'w': parent_orientation.w
        }
        
        json_data["parentID"] = str(parent_uuid)

    return json_data 
Example #5
Source File: test_uuid.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_uuid5(self):
        equal = self.assertEqual

        # Test some known version-5 UUIDs.
        for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
                      '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
                     (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
                      '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
                     (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
                      '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
                     (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
                      'cc957dd1-a972-5349-98cd-874190002798'),
                    ]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 5)
            equal(u, uuid.UUID(v))
            equal(str(u), v) 
Example #6
Source File: test_uuid.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_uuid5(self):
        equal = self.assertEqual

        # Test some known version-5 UUIDs.
        for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
                      '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
                     (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
                      '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
                     (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
                      '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
                     (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
                      'cc957dd1-a972-5349-98cd-874190002798'),
                    ]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 5)
            equal(u, uuid.UUID(v))
            equal(str(u), v) 
Example #7
Source File: qcontainer.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def dimm_device_define_by_params(self, params, name):
        """
        Create pc-dimm device from params.
        """
        params = params.object_params("dimm")
        dimm_type = "nvdimm" if params.get("nv_backend") else "pc-dimm"
        attrs = qdevices.Dimm.__attributes__[:]
        dev = qdevices.Dimm(params=params.copy_from_keys(attrs),
                            dimm_type=dimm_type)
        dev.set_param("id", "%s-%s" % ("dimm", name))
        if dimm_type == "nvdimm" and params.get("nvdimm_uuid"):
            try:
                dev.set_param("uuid", uuid.UUID(params["nvdimm_uuid"]))
            except ValueError:
                nvdimm_uuid = params["nvdimm_uuid"]
                if nvdimm_uuid == "<auto>":
                    nvdimm_uuid = uuid.uuid5(uuid.NAMESPACE_OID, name)
                dev.set_param("uuid", nvdimm_uuid)
        for ext_k, ext_v in params.get_dict("dimm_extra_params").items():
            dev.set_param(ext_k, ext_v)
        return dev 
Example #8
Source File: volatile.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def _fix(self):
        if self.uuid_template:
            return uuid.UUID(("%08x%04x%04x" + ("%02x" * 8))
                             % self.uuid_template)
        elif self.version == 1:
            return uuid.uuid1(self.node, self.clock_seq)
        elif self.version == 3:
            return uuid.uuid3(self.namespace, self.name)
        elif self.version == 4:
            return uuid.uuid4()
        elif self.version == 5:
            return uuid.uuid5(self.namespace, self.name)
        else:
            raise ValueError("Unhandled version")


# Automatic timestamp 
Example #9
Source File: artifacts.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def get_artifacts_by_keys(
    run: BaseRun, namespace: uuid.UUID, artifacts: List[V1RunArtifact]
) -> Dict:
    results = {}
    for m in artifacts:
        state = m.state
        if not state:
            if m.is_input:
                state = m.get_state(namespace)
            else:
                state = run.uuid
        elif not isinstance(state, uuid.UUID):
            try:
                state = uuid.UUID(state)
            except (ValueError, KeyError):
                state = uuid.uuid5(namespace, state)
        results[(m.name, state)] = m

    return results 
Example #10
Source File: test_uuid.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_uuid5(self):
        equal = self.assertEqual

        # Test some known version-5 UUIDs.
        for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),
                      '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
                     (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),
                      '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
                     (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),
                      '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
                     (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),
                      'cc957dd1-a972-5349-98cd-874190002798'),
                    ]:
            equal(u.variant, uuid.RFC_4122)
            equal(u.version, 5)
            equal(u, uuid.UUID(v))
            equal(str(u), v) 
Example #11
Source File: pypi.py    From dffml with MIT License 6 votes vote down vote up
def lookup(self, dependency: Dependency) -> Dependency:
        # Grab the package data from PyPi
        with urllib.request.urlopen(
            f"https://pypi.org/pypi/{dependency.name}/json"
        ) as resp:
            package_json = json.load(resp)
        return Dependency.mkoverride(
            dependency,
            url=package_json["info"]["project_urls"]["Homepage"],
            license=package_json["info"]["license"],
            extra={
                self.name: PyPiDependency(
                    uuid=None,
                    euuid=uuid.uuid5(self.uuid, dependency.name),
                    name=dependency.name,
                    url=f"https://pypi.org/pypi/{dependency.name}",
                    license=package_json["info"]["license"],
                )
            },
        ) 
Example #12
Source File: _lambda_build.py    From taskcat with Apache License 2.0 6 votes vote down vote up
def _build_lambdas(self, parent_path: Path, output_path):
        if not parent_path.is_dir():
            return
        for path in parent_path.iterdir():
            if (path / "Dockerfile").is_file():
                tag = f"taskcat-build-{uuid5(self.NULL_UUID, str(path)).hex}"
                LOG.info(
                    f"Packaging lambda source from {path} using docker image {tag}"
                )
                self._docker_build(path, tag)
                self._docker_extract(tag, output_path / path.stem)
            elif (path / "requirements.txt").is_file():
                LOG.info(f"Packaging python lambda source from {path} using pip")
                self._pip_build(path, output_path / path.stem)
            else:
                LOG.info(
                    f"Packaging lambda source from {path} without building "
                    f"dependencies"
                )
                self._zip_dir(path, output_path / path.stem) 
Example #13
Source File: metric.py    From biggraphite with Apache License 2.0 6 votes vote down vote up
def make_metric(name, metadata, created_on, updated_on, read_on):
    """Create a Metric object.

    Args:
      name: metric name.
      metadata: metric metadata.
      created_on: metric creation date.
      updated_on: metric last update date.
      read_on: metric last read date.

    Returns: a Metric object with a valid id.
    """
    encoded_name = encode_metric_name(sanitize_metric_name(name))
    uid = uuid.uuid5(_UUID_NAMESPACE, encoded_name)
    return Metric(
        encoded_name,
        uid,
        metadata,
        created_on=created_on,
        updated_on=updated_on,
        read_on=read_on,
    ) 
Example #14
Source File: database.py    From datasette with Apache License 2.0 6 votes vote down vote up
def execute_write_fn(self, fn, block=False):
        task_id = uuid.uuid5(uuid.NAMESPACE_DNS, "datasette.io")
        if self._write_queue is None:
            self._write_queue = queue.Queue()
        if self._write_thread is None:
            self._write_thread = threading.Thread(
                target=self._execute_writes, daemon=True
            )
            self._write_thread.start()
        reply_queue = janus.Queue()
        self._write_queue.put(WriteTask(fn, task_id, reply_queue))
        if block:
            result = await reply_queue.async_q.get()
            if isinstance(result, Exception):
                raise result
            else:
                return result
        else:
            return task_id 
Example #15
Source File: controller.py    From TobiiGlassesPyController with GNU General Public License v3.0 6 votes vote down vote up
def create_participant(self, project_id, participant_name = "DefaultUser", participant_notes = ""):
		participant_id = self.get_participant_id(participant_name)
		self.participant_name = participant_name

		if participant_id is None:
			data = {'pa_project': project_id,
					'pa_info': { 'EagleId': str(uuid.uuid5(uuid.NAMESPACE_DNS, self.participant_name)),
								 'Name': self.participant_name,
								 'Notes': participant_notes},
					'pa_created': self.__get_current_datetime__()}
			json_data = self.__post_request__('/api/participants', data)
			logging.debug("Participant " + json_data['pa_id'] + " created! Project " + project_id)
			return json_data['pa_id']
		else:
			logging.debug("Participant %s already exists ..." % participant_id)
			return participant_id 
Example #16
Source File: option_owners.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return uuid.uuid5(
            namespace=uuid.NAMESPACE_DNS,
            name=f"user<{self.user}>:"
            f"project<{self.project}>:"
            f"team<{self.team}>:"
            f"organization<{self.organization}>",
        ).hex 
Example #17
Source File: test_models.py    From cleanerversion with Apache License 2.0 5 votes vote down vote up
def test_create_with_uuid(self):
        p_id = self.uuid4()
        p = Person.objects.create(id=p_id, name="Alice")
        self.assertEqual(str(p_id), str(p.id))
        self.assertEqual(str(p_id), str(p.identity))

        p_id = uuid.uuid5(uuid.NAMESPACE_OID, str('bar'))
        with self.assertRaises(ValueError):
            Person.objects.create(id=p_id, name="Alexis") 
Example #18
Source File: schemas.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def get_state(self, namespace: uuid.UUID):
        if self.state:
            return self.state

        if self.path:
            return uuid.uuid5(namespace, self.path)

        return uuid.uuid5(namespace, str(self.summary)) 
Example #19
Source File: spec.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def uuid(self):
        return uuid.uuid5(uuid.NAMESPACE_DNS, self.__repr__()) 
Example #20
Source File: volumes.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def get_volume_name(path: str) -> str:
    name = uuid.uuid5(namespace=uuid.NAMESPACE_DNS, name=path).hex
    return constants.CONTEXT_VOLUME_CONNECTIONS_FORMAT.format(name) 
Example #21
Source File: directorybackedaddressbook.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def resourceID(self):
        if self.directory:
            resource_id = uuid.uuid5(uuid.UUID("5AAD67BF-86DD-42D7-9161-6AF977E4DAA3"), self.directory.guid).urn
        else:
            resource_id = "tag:unknown"
        return resource_id 
Example #22
Source File: resource.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def resourceID(self):
        return uuid.uuid5(self.uuid_namespace, str(self._newStoreHome.id())).urn 
Example #23
Source File: util.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def uuidFromName(namespace, name):
    """
    Generate a version 5 (SHA-1) UUID from a namespace UUID and a name.
    See http://www.ietf.org/rfc/rfc4122.txt, section 4.3.
    @param namespace: a UUID denoting the namespace of the generated UUID.
    @param name: a byte string to generate the UUID from.
    """
    # We don't want Unicode here; convert to UTF-8
    if type(name) is unicode:
        name = name.encode("utf-8")

    return normalizeUUID(str(uuid5(UUID(namespace), name))) 
Example #24
Source File: storebridge.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def resourceID(self):
        rid = "%s/%s" % (self._newStoreParentHome.id(), self._newStoreObject.id(),)
        return uuid.uuid5(self.uuid_namespace, rid).urn 
Example #25
Source File: icalsplitter.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def split(self, ical, rid=None, olderUID=None):
        """
        Split the specified iCalendar object. This assumes that L{willSplit} has already
        been called and returned C{True}. Splitting is done by carving out old instances
        into a new L{Component} and adjusting the specified component for the on-going
        set. A RELATED-TO property is added to link old to new.

        @param ical: the iCalendar object to split
        @type ical: L{Component}

        @param rid: recurrence-id where the split should occur, or C{None} to determine it here
        @type rid: L{DateTime} or C{None}

        @param olderUID: UID to use for the split off component, or C{None} to generate one here
        @type olderUID: C{str} or C{None}

        @return: iCalendar objects for the old and new "carved out" instances
        @rtype: C{tuple} of two L{Component}'s
        """

        # Find the instance RECURRENCE-ID where a split is going to happen
        rid = self.whereSplit(ical) if rid is None else rid

        # Create the old one with a new UID value (or the one passed in)
        icalOld = ical.duplicate()
        oldUID = icalOld.newUID(newUID=olderUID)
        icalOld.onlyPastInstances(rid)

        # Adjust the current one
        icalNew = ical.duplicate()
        icalNew.onlyFutureInstances(rid)

        # Relate them - add RELATED-TO;RELTYPE=RECURRENCE-SET if not already present
        if not icalOld.hasPropertyWithParameterMatch("RELATED-TO", "RELTYPE", "X-CALENDARSERVER-RECURRENCE-SET"):
            property = Property("RELATED-TO", str(uuid.uuid5(self.uuid_namespace, oldUID)), params={"RELTYPE": "X-CALENDARSERVER-RECURRENCE-SET"})
            icalOld.addPropertyToAllComponents(property)
            icalNew.addPropertyToAllComponents(property)

        return (icalOld, icalNew,) 
Example #26
Source File: pub_sub_api.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def generate_publisher_uuid():
    """
    Generate a non-random uuid based on the fully qualified domain name.
    This UUID is supposed to remain the same across service restarts.
    """
    fqdn = socket.getfqdn()
    process_name = df_utils.get_process_name()
    return str(uuid.uuid5(uuid.NAMESPACE_DNS,
               "{0}.{1}".format(process_name, fqdn))) 
Example #27
Source File: ids.py    From cti-stix-elevator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_sco_id(type, instance):
    required_prefix = type + "--"
    if not _SCO_CLASSES:
        # compute it once
        module = importlib.import_module("stix2.v21")
        for k, c in inspect.getmembers(module, inspect.isclass):
            if hasattr(c, "_properties") and "type" in c._properties:
                _SCO_CLASSES[c._properties["type"]._fixed_value] = c
    if type in _SCO_CLASSES:
        klass = _SCO_CLASSES[type]
        if klass and hasattr(klass, "_id_contributing_properties") and klass._id_contributing_properties:
            contributing_properties = klass._id_contributing_properties
            # streamlined_obj_vals = []
            streamlined_object = {}
            possible_hash = None
            if "hashes" in instance and "hashes" in contributing_properties:
                possible_hash = _choose_one_hash(instance["hashes"])
            if possible_hash:
                # streamlined_obj_vals.append(possible_hash)
                streamlined_object["hashes"] = possible_hash
            for key in contributing_properties:
                if key != "hashes" and key in instance:
                    # We don't need to handle the isinstance(...) cases here
                    # because the elevator uses Python default containers
                    # to represent its content.
                    # streamlined_obj_vals.append(instance[key])
                    streamlined_object[key] = instance[key]

            # if streamlined_obj_vals:
            if streamlined_object:
                # data = canonicalize(streamlined_obj_vals, utf8=False)
                data = canonicalize(streamlined_object, utf8=False)

                # try/except here to enable python 2 compatibility
                try:
                    return required_prefix + text_type(uuid.uuid5(SCO_DET_ID_NAMESPACE, data))
                except UnicodeDecodeError:
                    return required_prefix + text_type(uuid.uuid5(SCO_DET_ID_NAMESPACE, data.encode("utf-8")))

    return required_prefix + text_type(uuid.uuid4()) 
Example #28
Source File: _dataclasses.py    From taskcat with Apache License 2.0 5 votes vote down vote up
def generate_regional_bucket_name(region_obj: RegionObj, prefix: str = "tcat"):
    if len(prefix) > 8 or len(prefix) < 1:  # pylint: disable=len-as-condition
        raise TaskCatException("prefix must be between 1 and 8 characters long")
    hashed_account_id = uuid5(
        name=str(region_obj.account_id), namespace=UUID(int=0)
    ).hex
    return f"{prefix}-{hashed_account_id}-{region_obj.name}" 
Example #29
Source File: controller.py    From TobiiGlassesPyController with GNU General Public License v3.0 5 votes vote down vote up
def create_project(self, projectname = "DefaultProjectName"):
		project_id = self.get_project_id(projectname)

		if project_id is None:
			data = {'pr_info' : {'CreationDate': self.__get_current_datetime__(timeformat=TOBII_DATETIME_FORMAT_HUMREAD),
								 'EagleId':  str(uuid.uuid5(uuid.NAMESPACE_DNS, projectname)),
								 'Name': projectname},
					'pr_created': self.__get_current_datetime__() }
			json_data = self.__post_request__('/api/projects', data)
			logging.debug("Project %s created!" % json_data['pr_id'])
			return json_data['pr_id']
		else:
			logging.debug("Project %s already exists ..." % project_id)
			return project_id 
Example #30
Source File: controller.py    From TobiiGlassesPyController with GNU General Public License v3.0 5 votes vote down vote up
def create_recording(self, participant_id, recording_notes = ""):
		self.recn = self.recn + 1
		recording_name = "Recording_%s" % str(self.recn)
		data = {'rec_participant': participant_id,
				'rec_info': {'EagleId': str(uuid.uuid5(uuid.NAMESPACE_DNS, self.participant_name)),
							 'Name': recording_name,
							 'Notes': recording_notes},
							 'rec_created': self.__get_current_datetime__()}
		json_data = self.__post_request__('/api/recordings', data)
		return json_data['rec_id']