當前位置: 首頁>>代碼示例>>Python>>正文


Python uuid.UUID屬性代碼示例

本文整理匯總了Python中uuid.UUID屬性的典型用法代碼示例。如果您正苦於以下問題:Python uuid.UUID屬性的具體用法?Python uuid.UUID怎麽用?Python uuid.UUID使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在uuid的用法示例。


在下文中一共展示了uuid.UUID屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _parallelize_subtasks

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:airshipit,項目名稱:drydock,代碼行數:19,代碼來源:orchestrator.py

示例2: on_get

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:26,代碼來源:designs.py

示例3: get_task

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:20,代碼來源:tasks.py

示例4: post_result_message

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:airshipit,項目名稱:drydock,代碼行數:18,代碼來源:state.py

示例5: maintain_leadership

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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)) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:21,代碼來源:state.py

示例6: abdicate_leadership

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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)) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:20,代碼來源:state.py

示例7: get_boot_action

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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) 
開發者ID:airshipit,項目名稱:drydock,代碼行數:25,代碼來源:state.py

示例8: find_calendar_token

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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") 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:23,代碼來源:calendar_token.py

示例9: register_by_email_token_check

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:22,代碼來源:service.py

示例10: register_by_email_set_password

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:24,代碼來源:service.py

示例11: test_parse_message

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:19,代碼來源:test_ioctl.py

示例12: test_parse_message

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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) 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:18,代碼來源:test_create_contexts.py

示例13: _parse_value

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:19,代碼來源:structure.py

示例14: test_response_data

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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) 
開發者ID:deis,項目名稱:controller,代碼行數:21,代碼來源:test_release.py

示例15: test_dynamic_route_uuid

# 需要導入模塊: import uuid [as 別名]
# 或者: from uuid import UUID [as 別名]
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 
開發者ID:huge-success,項目名稱:sanic,代碼行數:23,代碼來源:test_routes.py


注:本文中的uuid.UUID屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。