Python uuid.UUID Examples

The following are 30 code examples for showing how to use uuid.UUID(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module uuid , or try the search function .

Example 1
Project: drydock   Author: airshipit   File: orchestrator.py    License: 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 2
Project: drydock   Author: airshipit   File: designs.py    License: 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 3
Project: drydock   Author: airshipit   File: tasks.py    License: 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 4
Project: drydock   Author: airshipit   File: state.py    License: 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 5
Project: drydock   Author: airshipit   File: state.py    License: 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 6
Project: drydock   Author: airshipit   File: state.py    License: 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 7
Project: drydock   Author: airshipit   File: state.py    License: Apache License 2.0 6 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 8
Project: everyclass-server   Author: everyclass   File: calendar_token.py    License: 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 9
Project: everyclass-server   Author: everyclass   File: service.py    License: 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 10
Project: everyclass-server   Author: everyclass   File: service.py    License: 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 11
Project: smbprotocol   Author: jborean93   File: test_ioctl.py    License: 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 12
Project: smbprotocol   Author: jborean93   File: test_create_contexts.py    License: 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 13
Project: smbprotocol   Author: jborean93   File: structure.py    License: 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
Project: controller   Author: deis   File: test_release.py    License: 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 15
Project: sanic   Author: huge-success   File: test_routes.py    License: 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
Project: gnocchi   Author: gnocchixyz   File: test_storage.py    License: 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 17
Project: gnocchi   Author: gnocchixyz   File: swift.py    License: 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 18
Project: gnocchi   Author: gnocchixyz   File: s3.py    License: 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 19
Project: gnocchi   Author: gnocchixyz   File: redis.py    License: 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 20
Project: gnocchi   Author: gnocchixyz   File: file.py    License: 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 21
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: 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 22
Project: zun   Author: openstack   File: short_id.py    License: 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 23
Project: drydock   Author: airshipit   File: orchestrator.py    License: Apache License 2.0 5 votes vote down vote up
def _collect_subtask_futures(self, subtask_futures, timeout=300):
        """Collect Futures executing on subtasks or timeout.

        Wait for Futures to finish or timeout. After timeout, enumerate the subtasks
        that timed out in task result messages.

        :param subtask_futures: dictionary of subtask_id.bytes -> Future instance
        :param timeout: The number of seconds to wait for all Futures to complete
        :param bubble: Whether to bubble results from collected subtasks
        """
        finished, timed_out = concurrent.futures.wait(
            subtask_futures.values(), timeout=timeout)

        for k, v in subtask_futures.items():
            if not v.done():
                self.task.add_status_msg(
                    "Subtask thread for %s still executing after timeout." %
                    str(uuid.UUID(bytes=k)),
                    error=True,
                    ctx=str(self.task.get_id()),
                    ctx_type='task')
                self.task.failure()
            else:
                if v.exception():
                    self.logger.error(
                        "Uncaught excetion in subtask %s future:" % str(
                            uuid.UUID(bytes=k)),
                        exc_info=v.exception())
            st = self.state_manager.get_task(uuid.UUID(bytes=k))
            st.bubble_results()
            st.align_result()
            st.save()
        if len(timed_out) > 0:
            raise errors.CollectSubtaskTimeout(
                "One or more subtask threads did not finish in %d seconds." %
                timeout)

        self.task.align_result()
        return 
Example 24
Project: drydock   Author: airshipit   File: designs.py    License: Apache License 2.0 5 votes vote down vote up
def on_post(self, req, resp):
        """Method handler for POST requests.

        :param req: Falcon request object
        :param resp: Falcon response object
        """
        try:
            json_data = self.req_json(req)
            design = None
            if json_data is not None:
                base_design = json_data.get('base_design_id', None)

                if base_design is not None:
                    base_design = uuid.UUID(base_design)
                    design = hd_objects.SiteDesign(base_design_id=base_design)
            else:
                design = hd_objects.SiteDesign()
            design.assign_id()
            design.create(req.context, self.state_manager)

            resp.body = json.dumps(design.obj_to_simple())
            resp.status = falcon.HTTP_201
        except errors.StateError:
            self.error(req.context, "Error updating persistence")
            self.return_error(
                resp,
                falcon.HTTP_500,
                message="Error updating persistence",
                retry=True)
        except errors.InvalidFormat as fex:
            self.error(req.context, str(fex))
            self.return_error(
                resp, falcon.HTTP_400, message=str(fex), retry=False) 
Example 25
Project: drydock   Author: airshipit   File: tasks.py    License: Apache License 2.0 5 votes vote down vote up
def on_get(self, req, resp, task_id):
        try:
            bd_list = self.state_manager.get_build_data(
                task_id=uuid.UUID(task_id))
            if not bd_list:
                resp.status = falcon.HTTP_404
                return
            resp.body = json.dumps([bd.to_dict() for bd in bd_list])
        except Exception as e:
            self.error(req.context, "Unknown error: %s" % (str(e)))
            resp.body = "Unexpected error."
            resp.status = falcon.HTTP_500
            return
        resp.status = falcon.HTTP_200 
Example 26
Project: drydock   Author: airshipit   File: builddata.py    License: Apache License 2.0 5 votes vote down vote up
def from_db(cls, d):
        """Create an instance from a DB-based dictionary.

        :param d: Dictionary of instance data
        """
        d['task_id'] = uuid.UUID(bytes=bytes(d.get('task_id')))

        i = BuildData(**d)

        return i


# Add BuildData to objects scope 
Example 27
Project: drydock   Author: airshipit   File: state.py    License: Apache License 2.0 5 votes vote down vote up
def get_complete_subtasks(self, task_id):
        """Query database for subtasks of the provided task that are complete.

        Complete is defined as status of Terminated or Complete.

        :param task_id: uuid.UUID ID of the parent task for subtasks
        """
        query_text = sql.text(
            "SELECT * FROM tasks WHERE "  # nosec no strings are user-sourced
            "parent_task_id = :parent_task_id AND status "
            "IN ('" + hd_fields.TaskStatus.Terminated + "','"
            + hd_fields.TaskStatus.Complete + "')")
        return self._query_subtasks(task_id, query_text,
                                    "Error querying complete subtask: %s") 
Example 28
Project: drydock   Author: airshipit   File: state.py    License: Apache License 2.0 5 votes vote down vote up
def get_active_subtasks(self, task_id):
        """Query database for subtasks of the provided task that are active.

        Active is defined as status of not Terminated or Complete. Returns
        list of objects.Task instances

        :param task_id: uuid.UUID ID of the parent task for subtasks
        """
        query_text = sql.text(
            "SELECT * FROM tasks WHERE "  # nosec no strings are user-sourced
            "parent_task_id = :parent_task_id AND status "
            "NOT IN ['" + hd_fields.TaskStatus.Terminated + "','"
            + hd_fields.TaskStatus.Complete + "']")
        return self._query_subtasks(task_id, query_text,
                                    "Error querying active subtask: %s") 
Example 29
Project: drydock   Author: airshipit   File: state.py    License: Apache License 2.0 5 votes vote down vote up
def get_all_subtasks(self, task_id):
        """Query database for all subtasks of the provided task.

        :param task_id: uuid.UUID ID of the parent task for subtasks
        """
        query_text = sql.text(
            "SELECT * FROM tasks WHERE "  # nosec no strings are user-sourced
            "parent_task_id = :parent_task_id")
        return self._query_subtasks(task_id, query_text,
                                    "Error querying all subtask: %s") 
Example 30
Project: drydock   Author: airshipit   File: state.py    License: Apache License 2.0 5 votes vote down vote up
def get_task(self, task_id):
        """Query database for task matching task_id.

        :param task_id: uuid.UUID of a task_id to query against
        """
        try:
            with self.db_engine.connect() as conn:
                query = self.tasks_tbl.select().where(
                    self.tasks_tbl.c.task_id == task_id.bytes)
                rs = conn.execute(query)
                r = rs.fetchone()

            task = objects.Task.from_db(dict(r))

            self.logger.debug(
                "Assembling result messages for task %s." % str(task.task_id))
            self._assemble_tasks(task_list=[task])
            task.statemgr = self

            return task

        except Exception as ex:
            self.logger.error(
                "Error querying task %s: %s" % (str(task_id), str(ex)),
                exc_info=True)
            return None