Python uuid.UUID Examples

The following are 30 code examples of uuid.UUID(). 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: state.py    From drydock with Apache License 2.0 7 votes vote down vote up
def get_boot_action(self, action_id):
        """Query for a single boot action by ID.

        :param action_id: string ULID bootaction id
        """
        try:
            with self.db_engine.connect() as conn:
                query = self.ba_status_tbl.select().where(
                    self.ba_status_tbl.c.action_id == ulid2.decode_ulid_base32(
                        action_id))
                rs = conn.execute(query)
                r = rs.fetchone()
                if r is not None:
                    ba_dict = dict(r)
                    ba_dict['action_id'] = bytes(ba_dict['action_id'])
                    ba_dict['identity_key'] = bytes(ba_dict['identity_key'])
                    ba_dict['task_id'] = uuid.UUID(bytes=ba_dict['task_id'])
                    return ba_dict
                else:
                    return None
        except Exception as ex:
            self.logger.error(
                "Error querying boot action %s" % action_id, exc_info=ex) 
Example #2
Source File: test_ioctl.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_parse_message(self):
        actual = SMB2ValidateNegotiateInfoRequest()
        data = b"\x08\x00\x00\x00" \
               b"\x11\x11\x11\x11\x11\x11\x11\x11" \
               b"\x11\x11\x11\x11\x11\x11\x11\x11" \
               b"\x01\x00" \
               b"\x02\x00" \
               b"\x02\x02\x10\x02"
        actual.unpack(data)
        assert len(actual) == 28
        assert actual['capabilities'].get_value() == 8
        assert actual['guid'].get_value() == uuid.UUID(bytes=b"\x11" * 16)
        assert actual['security_mode'].get_value() == 1
        assert actual['dialect_count'].get_value() == 2
        assert actual['dialects'][0] == 514
        assert actual['dialects'][1] == 528
        assert len(actual['dialects'].get_value()) == 2 
Example #3
Source File: redis.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def process_measures_for_sack(self, sack):
        results = self._scripts['process_measures_for_sack'](keys=[str(sack)])

        measures = {}
        for metric_id, item_len, data in results:
            try:
                metric_id = uuid.UUID(metric_id.decode())
            except ValueError:
                LOG.error("Unable to parse metric id %s, ignoring",
                          metric_id)
                continue
            measures[metric_id] = self._unserialize_measures(metric_id, data)

        yield measures

        pipe = self._client.pipeline()
        for metric_id, item_len, data in results:
            key = self._build_measure_path_with_sack(
                metric_id.decode(), str(sack))
            # ltrim is inclusive, bump 1 to remove up to and including nth item
            pipe.ltrim(key, item_len + 1, -1)
        pipe.execute() 
Example #4
Source File: swift.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def process_measures_for_sack(self, sack):
        measures = defaultdict(self._make_measures_array)
        sack_name = str(sack)
        headers, files = self.swift.get_container(sack_name, full_listing=True)
        for f in files:
            try:
                metric_id, random_id = f['name'].split("/")
                metric_id = uuid.UUID(metric_id)
            except ValueError:
                LOG.warning("Unable to parse measure file name %s", f)
                continue
            measures[metric_id] = self._array_concatenate([
                measures[metric_id],
                self._unserialize_measures(
                    metric_id,
                    self.swift.get_object(sack_name, f['name'])[1],
                )
            ])

        yield measures

        swift.bulk_delete(self.swift, sack_name, files) 
Example #5
Source File: s3.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def process_measures_for_sack(self, sack):
        measures = defaultdict(self._make_measures_array)
        files = self._list_measure_files((str(sack),))
        for f in files:
            try:
                sack, metric_id, measure_id = f.split("/")
                metric_id = uuid.UUID(metric_id)
            except ValueError:
                LOG.warning("Unable to parse measure file name %s", f)
                continue

            response = self.s3.get_object(
                Bucket=self._bucket_name_measures,
                Key=f)
            measures[metric_id] = numpy.concatenate((
                measures[metric_id],
                self._unserialize_measures(f, response['Body'].read())
            ))

        yield measures

        # Now clean objects
        s3.bulk_delete(self.s3, self._bucket_name_measures, files) 
Example #6
Source File: file.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def process_measures_for_sack(self, sack):
        measures = {}
        processed_files = {}
        for metric_id in self._list_target(self._sack_path(sack)):
            try:
                metric_id = uuid.UUID(metric_id)
            except ValueError:
                LOG.error("Unable to parse %s as an UUID, ignoring metric",
                          metric_id)
                continue
            files = self._list_measures_container_for_metric_str(
                sack, metric_id)
            processed_files[metric_id] = files
            m = self._make_measures_array()
            for f in files:
                abspath = self._build_measure_path(metric_id, f)
                with open(abspath, "rb") as e:
                    m = numpy.concatenate((
                        m, self._unserialize_measures(f, e.read())))
            measures[metric_id] = m

        yield measures

        for metric_id, files in six.iteritems(processed_files):
            self._delete_measures_files_for_metric(metric_id, files) 
Example #7
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def get_task(self, req, resp, task_id, builddata):
        try:
            task = self.state_manager.get_task(uuid.UUID(task_id))
            if task is None:
                return None

            task_dict = task.to_dict()

            if builddata:
                task_bd = self.state_manager.get_build_data(
                    task_id=task.get_id())
                task_dict['build_data'] = [bd.to_dict() for bd in task_bd]

            return task_dict
        except Exception as ex:
            self.error(req.context, "Unknown error: %s" % (str(ex)))
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False) 
Example #8
Source File: designs.py    From drydock with Apache License 2.0 6 votes vote down vote up
def on_get(self, req, resp, design_id):
        """Method Handler for GET design singleton.

        :param req: Falcon request object
        :param resp: Falcon response object
        :param design_id: UUID of the design resource
        """
        source = req.params.get('source', 'designed')

        try:
            design = None
            if source == 'compiled':
                design = self.orchestrator.get_effective_site(design_id)
            elif source == 'designed':
                design = self.orchestrator.get_described_site(design_id)

            resp.body = json.dumps(design.obj_to_simple())
        except errors.DesignError:
            self.error(req.context, "Design %s not found" % design_id)
            self.return_error(
                resp,
                falcon.HTTP_404,
                message="Design %s not found" % design_id,
                retry=False) 
Example #9
Source File: tests.py    From pyspark-cassandra with Apache License 2.0 6 votes vote down vote up
def test_89(self):
        self.session.execute('''
            CREATE TABLE IF NOT EXISTS test_89 (
                id text PRIMARY KEY,
                val text
            )
        ''')
        self.session.execute('''TRUNCATE test_89''')

        self.sc.parallelize([dict(id='a', val='b')]).saveToCassandra(self.keyspace, 'test_89')
        joined = (self.sc
            .parallelize([dict(id='a', uuid=UUID('27776620-e46e-11e5-a837-0800200c9a66'))])
            .joinWithCassandraTable(self.keyspace, 'test_89')
            .collect()
        )

        self.assertEqual(len(joined), 1)
        self.assertEqual(len(joined[0]), 2)
        left, right = joined[0]
        self.assertEqual(left['id'], 'a')
        self.assertEqual(left['uuid'], UUID('27776620-e46e-11e5-a837-0800200c9a66'))
        self.assertEqual(right['id'], 'a')
        self.assertEqual(right['val'], 'b') 
Example #10
Source File: short_id.py    From zun with Apache License 2.0 6 votes vote down vote up
def get_id(source_uuid):
    """Derive a short (12 character) id from a random UUID.

    The supplied UUID must be a version 4 UUID object.
    """

    if isinstance(source_uuid, str):
        source_uuid = uuid.UUID(source_uuid)
    if source_uuid.version != 4:
        raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)

    # The "time" field of a v4 UUID contains 60 random bits
    # (see RFC4122, Section 4.4)
    random_bytes = _to_byte_string(source_uuid.time, 60)
    # The first 12 bytes (= 60 bits) of base32-encoded output is our data
    encoded = base64.b32encode(random_bytes.encode("latin-1"))[:12]

    return encoded.lower().decode('utf-8') 
Example #11
Source File: orchestrator.py    From drydock with Apache License 2.0 6 votes vote down vote up
def _parallelize_subtasks(self, fn, subtask_id_list, *args, **kwargs):
        """Spawn threads to execute fn for each subtask using concurrent.futures.

        Return a dictionary of task_id:concurrent.futures.Future instance

        :param fn: The callable to execute in a thread, expected it takes a task_id as first argument
        :param subtask_id_list: List of uuid.UUID ID of the subtasks to execute on
        :param *args: The args to pass to fn
        :param **kwargs: The kwargs to pass to fn
        """
        task_futures = dict()

        with concurrent.futures.ThreadPoolExecutor(max_workers=16) as te:
            for t in subtask_id_list:
                task_futures[t.bytes] = te.submit(fn, t, *args, **kwargs)

        return task_futures 
Example #12
Source File: state.py    From drydock with Apache License 2.0 6 votes vote down vote up
def post_result_message(self, task_id, msg):
        """Add a result message to database attached to task task_id.

        :param task_id: uuid.UUID ID of the task the msg belongs to
        :param msg: instance of objects.TaskStatusMessage
        """
        try:
            with self.db_engine.connect() as conn:
                query = self.result_message_tbl.insert().values(
                    task_id=task_id.bytes, **(msg.to_db()))
                conn.execute(query)
            return True
        except Exception as ex:
            self.logger.error("Error inserting result message for task %s: %s"
                              % (str(task_id), str(ex)))
            return False 
Example #13
Source File: structure.py    From smbprotocol with MIT License 6 votes vote down vote up
def _parse_value(self, value):
        if value is None:
            uuid_value = uuid.UUID(bytes=b"\x00" * 16)
        elif isinstance(value, bytes) and self.little_endian:
            uuid_value = uuid.UUID(bytes=value)
        elif isinstance(value, bytes) and not self.little_endian:
            uuid_value = uuid.UUID(bytes_le=value)
        elif isinstance(value, integer_types):
            uuid_value = uuid.UUID(int=value)
        elif isinstance(value, uuid.UUID):
            uuid_value = value
        elif isinstance(value, types.LambdaType):
            uuid_value = value
        else:
            raise TypeError("Cannot parse value for field %s of type %s to a "
                            "uuid" % (self.name, type(value).__name__))
        return uuid_value 
Example #14
Source File: state.py    From drydock with Apache License 2.0 6 votes vote down vote up
def maintain_leadership(self, leader_id):
        """The active leader reaffirms its existence.

        :param leader_id: uuid.UUID ID of the leader
        """
        try:
            with self.db_engine.connect() as conn:
                query = self.active_instance_tbl.update().where(
                    self.active_instance_tbl.c.identity == leader_id.
                    bytes).values(last_ping=datetime.utcnow())
                rs = conn.execute(query)
                rc = rs.rowcount

                if rc == 1:
                    return True
                else:
                    return False
        except Exception as ex:
            self.logger.error("Error maintaining leadership: %s" % str(ex)) 
Example #15
Source File: test_routes.py    From sanic with MIT License 6 votes vote down vote up
def test_dynamic_route_uuid(app):
    import uuid

    results = []

    @app.route("/quirky/<unique_id:uuid>")
    async def handler(request, unique_id):
        results.append(unique_id)
        return text("OK")

    url = "/quirky/123e4567-e89b-12d3-a456-426655440000"
    request, response = app.test_client.get(url)
    assert response.text == "OK"
    assert type(results[0]) is uuid.UUID

    generated_uuid = uuid.uuid4()
    request, response = app.test_client.get(f"/quirky/{generated_uuid}")
    assert response.status == 200

    request, response = app.test_client.get("/quirky/non-existing")
    assert response.status == 404 
Example #16
Source File: service.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def register_by_email_set_password(request_id: str, password: str) -> str:
    """通过邮件注册-设置密码,注册成功返回学号/教工号"""
    req = VerificationRequest.find_by_id(uuid.UUID(request_id))
    if not req:
        raise IdentityVerifyRequestNotFoundError

    if req.status == VerificationRequest.STATUS_PASSWORD_SET:
        # 已经注册,重复请求,当做成功
        return req.identifier

    if req.status != VerificationRequest.STATUS_TKN_PASSED:
        raise IdentityVerifyRequestStatusError

    # 密码强度检查
    if score_password_strength(password) < 2:
        record_simple_password(password=password, identifier=req.identifier)
        raise PasswordTooWeakError

    add_user(req.identifier, password, False)

    req.set_status_password_set()
    return req.identifier 
Example #17
Source File: service.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def register_by_email_token_check(token: str) -> str:
    """检查邮件验证token有效性,并返回verification requestID"""
    with tracer.trace('verify_email_token'):
        rpc_result = Auth.verify_email_token(token=token)

    if not rpc_result.success:
        raise InvalidTokenError

    request = VerificationRequest.find_by_id(uuid.UUID(rpc_result.request_id))
    if not request:
        logger.error(f"can not find related verification request of email token {token}")
    if request.status != VerificationRequest.STATUS_TKN_PASSED:
        request.set_status_token_passed()

    student_id = request.identifier
    if user_exist(student_id):
        logger.info(f"User {student_id} try to register again by email token. Request filtered.")
        raise AlreadyRegisteredError

    return rpc_result.request_id 
Example #18
Source File: test_create_contexts.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_parse_message(self):
        actual = SMB2CreateDurableHandleRequestV2()
        data = b"\x64\x00\x00\x00" \
               b"\x02\x00\x00\x00" \
               b"\x00\x00\x00\x00\x00\x00\x00\x00" \
               b"\xff\xff\xff\xff\xff\xff\xff\xff" \
               b"\xff\xff\xff\xff\xff\xff\xff\xff"
        data = actual.unpack(data)
        assert len(actual) == 32
        assert data == b""
        assert actual['timeout'].get_value() == 100
        assert actual['flags'].get_value() == \
            DurableHandleFlags.SMB2_DHANDLE_FLAG_PERSISTENT
        assert actual['reserved'].get_value() == 0
        assert actual['create_guid'].get_value() == \
            uuid.UUID(bytes=b"\xff" * 16) 
Example #19
Source File: calendar_token.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def find_calendar_token(tid=None, sid=None, semester=None, token=None):
    """通过 token 或者 sid/tid + 学期获得 token 文档"""
    with pg_conn_context() as conn, conn.cursor() as cursor:
        if token:
            select_query = """
            SELECT type, identifier, semester, token, create_time, last_used_time FROM calendar_tokens
                WHERE token=%s
            """
            cursor.execute(select_query, (uuid.UUID(token),))
            result = cursor.fetchall()
            return _parse(result[0]) if result else None
        elif (tid or sid) and semester:
            select_query = """
            SELECT type, identifier, semester, token, create_time, last_used_time FROM calendar_tokens
                WHERE type=%s AND identifier=%s AND semester=%s;
            """
            cursor.execute(select_query, ("teacher" if tid else "student", tid, semester))
            result = cursor.fetchall()
            return _parse(result[0]) if result else None
        else:
            raise ValueError("tid/sid together with semester or token must be given to search a token document") 
Example #20
Source File: test_release.py    From controller with MIT License 6 votes vote down vote up
def test_response_data(self, mock_requests):
        app_id = self.create_app()
        body = {'values': json.dumps({'NEW_URL': 'http://localhost:8080/'})}
        url = '/v2/apps/{}/config'.format(app_id)
        config_response = self.client.post(url, body)
        url = '/v2/apps/{}/releases/v2'.format(app_id)
        response = self.client.get(url)
        for key in response.data.keys():
            self.assertIn(key, ['uuid', 'owner', 'created', 'updated', 'app', 'build', 'config',
                                'summary', 'version', 'failed'])
        expected = {
            'owner': self.user.username,
            'app': app_id,
            'build': None,
            'config': uuid.UUID(config_response.data['uuid']),
            'summary': '{} added NEW_URL'.format(self.user.username),
            'version': 2
        }
        self.assertDictContainsSubset(expected, response.data) 
Example #21
Source File: test_storage.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def test_file_driver_subdir_len(self):
        driver = storage.get_driver(self.conf)
        if not isinstance(driver, file.FileStorage):
            self.skipTest("not file driver")

        # Check the default
        self.assertEqual(2, driver.SUBDIR_LEN)

        metric = mock.Mock(id=uuid.UUID("12345678901234567890123456789012"))
        expected = (driver.basepath + "/12/34/56/78/90/12/34/56/78/90/12/34/56"
                    "/78/90/12/12345678-9012-3456-7890-123456789012")
        self.assertEqual(expected, driver._build_metric_dir(metric))

        driver._file_subdir_len = 16
        expected = (driver.basepath + "/1234567890123456/7890123456"
                    "789012/12345678-9012-3456-7890-123456789012")
        self.assertEqual(expected, driver._build_metric_dir(metric))

        driver._file_subdir_len = 15
        expected = (driver.basepath + "/123456789012345/67890123456"
                    "7890/12/12345678-9012-3456-7890-123456789012")
        self.assertEqual(expected, driver._build_metric_dir(metric)) 
Example #22
Source File: state.py    From drydock with Apache License 2.0 6 votes vote down vote up
def abdicate_leadership(self, leader_id):
        """Give up leadership for ``leader_id``.

        :param leader_id: a uuid.UUID instance identifying the instance giving up leadership
        """
        try:
            with self.db_engine.connect() as conn:
                query = self.active_instance_tbl.delete().where(
                    self.active_instance_tbl.c.identity == leader_id.bytes)
                rs = conn.execute(query)
                rc = rs.rowcount

            if rc == 1:
                return True
            else:
                return False
        except Exception as ex:
            self.logger.error("Error abidcating leadership: %s" % str(ex)) 
Example #23
Source File: test_file_info.py    From smbprotocol with MIT License 5 votes vote down vote up
def test_parse_message(self):
        actual = FileFsObjectIdInformation()
        data = actual.unpack(self.DATA)

        assert len(actual) == 64
        assert data == b""

        assert actual['object_id'].get_value() == uuid.UUID(
            bytes=b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
        )
        assert actual['extended_info'].get_value() == b"\x00" * 48 
Example #24
Source File: tag.py    From quart with MIT License 5 votes vote down vote up
def to_python(self, value: str) -> UUID:
        return UUID(value) 
Example #25
Source File: test_connection.py    From smbprotocol with MIT License 5 votes vote down vote up
def test_create_message(self):
        message = SMB2NegotiateRequest()
        message['security_mode'] = SecurityMode.SMB2_NEGOTIATE_SIGNING_ENABLED
        message['capabilities'] = 10
        message['client_guid'] = uuid.UUID(bytes=b"\x33" * 16)
        message['dialects'] = [
            Dialects.SMB_2_0_2,
            Dialects.SMB_2_1_0,
            Dialects.SMB_3_0_0,
            Dialects.SMB_3_0_2
        ]
        expected = b"\x24\x00" \
                   b"\x04\x00" \
                   b"\x01\x00" \
                   b"\x00\x00" \
                   b"\x0a\x00\x00\x00" \
                   b"\x33\x33\x33\x33\x33\x33\x33\x33" \
                   b"\x33\x33\x33\x33\x33\x33\x33\x33" \
                   b"\x00\x00\x00\x00\x00\x00\x00\x00" \
                   b"\x02\x02" \
                   b"\x10\x02" \
                   b"\x00\x03" \
                   b"\x02\x03"
        actual = message.pack()
        assert len(message) == 44
        assert actual == expected 
Example #26
Source File: test_structure.py    From smbprotocol with MIT License 5 votes vote down vote up
def test_set_none(self):
        field = self.StructureTest()['field']
        field.set_value(None)
        expected = uuid.UUID("00000000-0000-0000-0000-000000000000")
        actual = field.get_value()
        assert isinstance(field.value, uuid.UUID)
        assert actual == expected 
Example #27
Source File: structure.py    From smbprotocol with MIT License 5 votes vote down vote up
def __init__(self, size=None, **kwargs):
        """
        Used to store a UUID (GUID) as a Python UUID object.

        :param size: Must be set to None or 16, this is so we can
            check/override
        :param kwargs: Any other kwarg to be sent to Field()
        """
        if not (size is None or size == 16):
            raise InvalidFieldDefinition("UuidField type must have a size of "
                                         "16 not %d" % size)
        super(UuidField, self).__init__(size=16, **kwargs) 
Example #28
Source File: __init__.py    From quart with MIT License 5 votes vote down vote up
def default(self, object_: Any) -> Any:
        if isinstance(object_, date):
            return formatdate(timeval=mktime((object_.timetuple())), localtime=False, usegmt=True)
        if isinstance(object_, UUID):
            return str(object_)
        if hasattr(object_, "__html__"):
            return str(object_.__html__())
        return super().default(object_) 
Example #29
Source File: tag.py    From quart with MIT License 5 votes vote down vote up
def check(self, value: Any) -> bool:
        return isinstance(value, UUID) 
Example #30
Source File: test_connection.py    From smbprotocol with MIT License 5 votes vote down vote up
def test_create_message_one_dialect(self):
        message = SMB3NegotiateRequest()
        message['security_mode'] = SecurityMode.SMB2_NEGOTIATE_SIGNING_ENABLED
        message['capabilities'] = 10
        message['client_guid'] = uuid.UUID(bytes=b"\x33" * 16)
        message['dialects'] = [
            Dialects.SMB_3_1_1
        ]
        con_req = SMB2NegotiateContextRequest()
        con_req['context_type'] = \
            NegotiateContextType.SMB2_ENCRYPTION_CAPABILITIES

        enc_cap = SMB2EncryptionCapabilities()
        enc_cap['ciphers'] = [Ciphers.AES_128_GCM]
        con_req['data'] = enc_cap
        message['negotiate_context_list'] = [
            con_req
        ]
        expected = b"\x24\x00" \
                   b"\x01\x00" \
                   b"\x01\x00" \
                   b"\x00\x00" \
                   b"\x0a\x00\x00\x00" \
                   b"\x33\x33\x33\x33\x33\x33\x33\x33" \
                   b"\x33\x33\x33\x33\x33\x33\x33\x33" \
                   b"\x68\x00\x00\x00" \
                   b"\x01\x00" \
                   b"\x00\x00" \
                   b"\x11\x03" \
                   b"\x00\x00" \
                   b"\x02\x00\x04\x00\x00\x00\x00\x00" \
                   b"\x01\x00\x02\x00" \
                   b"\x00\x00\x00\x00"
        actual = message.pack()
        assert len(message) == 56
        assert actual == expected