Python uuid.uuid4() Examples

The following are 30 code examples for showing how to use uuid.uuid4(). 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: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def test_object_PUT_at_id(self):
        """Create object in collection using PUT at specific ID."""
        index = self.client.get("/{}".format(self.API_NAME))
        assert index.status_code == 200
        endpoints = json.loads(index.data.decode('utf-8'))
        for endpoint in endpoints:
            collection_name = "/".join(endpoints[endpoint].split(
                "/{}/".format(self.API_NAME))[1:])
            if collection_name in self.doc.collections:
                collection = self.doc.collections[collection_name]["collection"]
                class_ = self.doc.parsed_classes[collection.class_.title]["class"]
                class_methods = [x.method for x in class_.supportedOperation]
                dummy_object = gen_dummy_object(
                    collection.class_.title, self.doc)
                if "PUT" in class_methods:
                    dummy_object = gen_dummy_object(
                        collection.class_.title, self.doc)
                    put_response = self.client.put('{}/{}'.format(
                        endpoints[endpoint], uuid.uuid4()), data=json.dumps(dummy_object))
                    assert put_response.status_code == 201 
Example 2
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def test_object_PUT_at_ids(self):
        index = self.client.get("/{}".format(self.API_NAME))
        assert index.status_code == 200
        endpoints = json.loads(index.data.decode('utf-8'))
        for endpoint in endpoints:
            collection_name = "/".join(endpoints[endpoint].split(
                "/{}/".format(self.API_NAME))[1:])
            if collection_name in self.doc.collections:
                collection = self.doc.collections[collection_name]["collection"]
                class_ = self.doc.parsed_classes[collection.class_.title]["class"]
                class_methods = [x.method for x in class_.supportedOperation]
                data_ = {"data": list()}
                objects = list()
                ids = ""
                for index in range(3):
                    objects.append(gen_dummy_object(
                        collection.class_.title, self.doc))
                    ids = "{},".format(uuid.uuid4())
                data_["data"] = objects
                if "PUT" in class_methods:
                    put_response = self.client.put(
                        '{}/add/{}'.format(endpoints[endpoint], ids),
                        data=json.dumps(data_))
                    assert put_response.status_code == 201 
Example 3
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            class_title = self.doc.parsed_classes[class_]["class"].title
            dummy_obj = gen_dummy_object(class_title, self.doc)
            crud.insert(
                dummy_obj,
                id_=str(
                    uuid.uuid4()),
                session=self.session)
            # If it's a collection class then add an extra object so
            # we can test pagination thoroughly.
            if class_ in self.doc.collections:
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session)
        # Add two dummy modification records
        crud.insert_modification_record(method="POST",
                                        resource_url="", session=self.session)
        crud.insert_modification_record(method="DELETE",
                                        resource_url="", session=self.session) 
Example 4
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_update(self):
        """Test CRUD update."""
        random_class = random.choice(self.doc_collection_classes)
        object_ = gen_dummy_object(random_class, self.doc)
        new_object = gen_dummy_object(random_class, self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        update_response = crud.update(
            id_=id_,
            type_=object_["@type"],
            object_=new_object,
            session=self.session,
            api_name="api")
        test_object = crud.get(id_=id_, type_=object_[
                               "@type"], session=self.session, api_name="api")
        assert isinstance(insert_response, str)
        assert isinstance(update_response, str)
        assert insert_response == update_response
        assert test_object["@id"].split("/")[-1] == id_ 
Example 5
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete(self):
        """Test CRUD delete."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        delete_response = crud.delete(
            id_=id_, type_=object_["@type"], session=self.session)
        assert isinstance(insert_response, str)
        response_code = None
        try:
            get_response = crud.get(
                id_=id_,
                type_=object_["@type"],
                session=self.session,
                api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 6
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_type(self):
        """Test CRUD delete when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        assert isinstance(insert_response, str)
        assert insert_response == id_
        response_code = None
        try:
            delete_response = crud.delete(
                id_=id_, type_="otherClass", session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 7
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_id(self):
        """Test CRUD delete when wrong/undefined ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            delete_response = crud.delete(
                id_=999, type_=object_["@type"], session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code
        assert isinstance(insert_response, str)
        assert insert_response == id_ 
Example 8
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_ids(self):
        objects = list()
        ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
        for index in range(len(ids.split(','))):
            object = gen_dummy_object(random.choice(
                self.doc_collection_classes), self.doc)
            objects.append(object)
        insert_response = crud.insert_multiple(objects_=objects,
                                               session=self.session, id_=ids)
        delete_response = crud.delete_multiple(
            id_=ids, type_=objects[0]["@type"], session=self.session)

        response_code = None
        id_list = ids.split(',')
        try:
            for index in range(len(id_list)):
                get_response = crud.get(
                    id_=id_list[index],
                    type_=objects[index]["@type"],
                    session=self.session,
                    api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 9
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    License: Apache License 2.0 6 votes vote down vote up
def test_build_data_insert_iwth_collected_date(self, blank_state):
        """Test that build data can be inserted specifying collection date."""
        build_data_fields = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data = objects.BuildData(**build_data_fields)

        result = blank_state.post_build_data(build_data)

        assert result 
Example 10
Project: drydock   Author: airshipit   File: test_postgres_builddata.py    License: Apache License 2.0 6 votes vote down vote up
def test_build_data_select(self, blank_state):
        """Test that build data can be deserialized from the database."""
        build_data_fields = {
            'node_name': 'foo',
            'generator': 'hello_world',
            'data_format': 'text/plain',
            'data_element': 'Hello World!',
            'task_id': uuid.uuid4(),
            'collected_date': datetime.utcnow(),
        }

        build_data = objects.BuildData(**build_data_fields)

        result = blank_state.post_build_data(build_data)

        assert result

        bd_list = blank_state.get_build_data()

        assert len(bd_list) == 1

        assert bd_list[0].to_dict() == build_data.to_dict() 
Example 11
Project: drydock   Author: airshipit   File: test_maasdriver_network.py    License: Apache License 2.0 6 votes vote down vote up
def test_maas_fabric(self):
        client_config = config.DrydockConfig.node_driver['maasdriver']

        maas_client = client.MaasRequestFactory(client_config['api_url'],
                                                client_config['api_key'])

        fabric_name = str(uuid.uuid4())

        fabric_list = maas_fabric.Fabrics(maas_client)
        fabric_list.refresh()

        test_fabric = maas_fabric.Fabric(
            maas_client, name=fabric_name, description='Test Fabric')
        test_fabric = fabric_list.add(test_fabric)

        assert test_fabric.name == fabric_name
        assert test_fabric.resource_id is not None

        query_fabric = maas_fabric.Fabric(
            maas_client, resource_id=test_fabric.resource_id)
        query_fabric.refresh()

        assert query_fabric.name == test_fabric.name 
Example 12
Project: drydock   Author: airshipit   File: test_auth_middleware.py    License: Apache License 2.0 6 votes vote down vote up
def test_process_request_user(self):
        ''' AuthMiddleware is expected to correctly identify the headers
            added to an authenticated request by keystonemiddleware in a
            PasteDeploy configuration
        '''

        req_env = TestAuthMiddleware.ks_user_env

        project_id = str(uuid.uuid4().hex)
        req_env['HTTP_X_PROJECT_ID'] = project_id
        user_id = str(uuid.uuid4().hex)
        req_env['HTTP_X_USER_ID'] = user_id
        token = str(uuid.uuid4().hex)
        req_env['HTTP_X_AUTH_TOKEN'] = token

        middleware = AuthMiddleware()
        request = DrydockRequest(req_env)
        response = falcon.Response()

        middleware.process_request(request, response)

        assert request.context.authenticated
        assert request.context.user_id == user_id 
Example 13
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow3.py    License: MIT License 6 votes vote down vote up
def session_id(self):
        """A unique session ID every time the user uses the workflow.

        .. versionadded:: 1.25

        The session ID persists while the user is using this workflow.
        It expires when the user runs a different workflow or closes
        Alfred.

        """
        if not self._session_id:
            from uuid import uuid4
            self._session_id = uuid4().hex
            self.setvar('_WF_SESSION_ID', self._session_id)

        return self._session_id 
Example 14
Project: everyclass-server   Author: everyclass   File: calendar_token.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def insert_calendar_token(resource_type: str, semester: str, identifier: str) -> str:
    """
    生成日历令牌,写入数据库并返回字符串类型的令牌。此时的 last_used_time 是 NULL。

    :param resource_type: student/teacher
    :param semester: 学期字符串
    :param identifier: 学号或教工号
    :return: token 字符串
    """
    token = uuid.uuid4()

    with pg_conn_context() as conn, conn.cursor() as cursor:
        insert_query = """
        INSERT INTO calendar_tokens (type, identifier, semester, token, create_time)
            VALUES (%s,%s,%s,%s,%s);
        """
        cursor.execute(insert_query, (resource_type, identifier, semester, token, datetime.datetime.now()))
        conn.commit()
    return str(token) 
Example 15
Project: everyclass-server   Author: everyclass   File: verification_request.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def _new_request(cls, identifier: str, verification_method: str, status: str, password: str = None) -> str:
        """
        新增一条注册请求

        :param identifier: 学号/教工号
        :param verification_method: password or email
        :param status: status of the request
        :param password: if register by password, fill everyclass password here
        :return: the `request_id`
        """
        if verification_method not in (cls.METHOD_PASSWORD, cls.METHOD_EMAIL):
            raise ValueError("verification_method must be one of email and password")

        request_id = uuid.uuid4()

        extra_doc = {}
        if password:
            extra_doc.update({"password": generate_password_hash(password)})

        request = VerificationRequest(request_id=request_id, identifier=identifier, method=verification_method,
                                      status=status, extra=extra_doc)
        db_session.add(request)
        db_session.commit()

        return str(request_id) 
Example 16
Project: MPContribs   Author: materialsproject   File: tdata.py    License: MIT License 6 votes vote down vote up
def render(self, total_records=None):
        """use BackGrid JS library to render Pandas DataFrame"""
        # if project given, this will result in an overview table of contributions
        # TODO check for index column in df other than the default numbering
        jtable = json.dumps(self.to_backgrid_dict())
        if total_records is None:
            total_records = self.shape[0]
        config = {"total_records": total_records}
        config["uuids"] = [str(uuid.uuid4()) for i in range(4)]
        if self.tid:
            config["tid"] = self.tid
            config["per_page"] = self.per_page
        else:
            config["project"] = self.project
        config["api_key"] = self.api_key
        config["ncols"] = self.ncols
        config["filters"] = self.filters
        jconfig = json.dumps(config)
        html = '<div class="col-md-6" id="{}"></div>'.format(config["uuids"][0])
        html += '<div class="pull-right" id="{}"></div>'.format(config["uuids"][3])
        html += '<div id="{}" style="width:100%;"></div>'.format(config["uuids"][1])
        html += '<div id="{}"></div>'.format(config["uuids"][2])
        html += f"<script>render_table({{table: {jtable}, config: {jconfig}}})</script>"
        return html 
Example 17
Project: ciocheck   Author: ContinuumIO   File: utils.py    License: MIT License 6 votes vote down vote up
def _rename_over_existing(src, dest):
    try:
        # On Windows, this will throw EEXIST, on Linux it won't.
        os.rename(src, dest)
    except IOError as err:
        if err.errno == errno.EEXIST:
            # Clearly this song-and-dance is not in fact atomic,
            # but if something goes wrong putting the new file in
            # place at least the backup file might still be
            # around.
            backup = "{0}.bak-{1}".format(dest, str(uuid.uuid4()))
            os.rename(dest, backup)
            try:
                os.rename(src, dest)
            except Exception as err:
                os.rename(backup, dest)
                raise err
            finally:
                try:
                    os.remove(backup)
                except Exception as err:
                    pass 
Example 18
Project: pgrepup   Author: rtshome   File: database.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_pg_hba_contents(conn):
    pg_hba_path = get_setting_value(conn, "hba_file")
    if not pg_hba_path:
        return None

    try:
        temp_table = "pghba_" + uuid.uuid4().hex
        cur = conn.cursor()
        cur.execute("CREATE TEMP TABLE " + temp_table + " (content text)")
        cur.execute("COPY " + temp_table + " FROM %s", [pg_hba_path])
        cur.execute("SELECT * FROM " + temp_table + ";")
        rows = cur.fetchall()
        conn.rollback()
        return rows
    except psycopg2.Error as e:
        print(e)
        return None 
Example 19
Project: vergeml   Author: mme   File: dataset.py    License: MIT License 5 votes vote down vote up
def download_files(self, urls, env, headers=None, dir=None):

        if dir is None:
            dir = env.get('cache-dir')
        
        dest_directory = os.path.join(dir, "tmp_" + str(uuid.uuid4()))
        
        if not os.path.exists(dest_directory):
            os.makedirs(dest_directory)

        for data_url in urls:
            if isinstance(data_url, tuple):
                data_url, download_file = data_url
            else:
                download_file = data_url.split('/')[-1]

            download_path = os.path.join(dest_directory, download_file)

            if headers:
                opener = urllib.request.build_opener()
                opener.addheaders = headers
                urllib.request.install_opener(opener)

            try:
                urllib.request.urlretrieve(data_url, filename=download_path, 
                                           reporthook=self._report_hook(download_file), data=None)
            except Exception as e:
                raise VergeMLError("Could not download {}: {}".format(data_url, e))
            finally:
                if headers:
                    urllib.request.install_opener(urllib.request.build_opener())

        return dest_directory 
Example 20
Project: hydrus   Author: HTTP-APIs   File: user.py    License: MIT License 5 votes vote down vote up
def create_nonce(session: Session) -> str:
    """
    Create a one time use nonce valid for a short time
    for user authentication.
    """
    nonce = str(uuid4())
    time = datetime.now()
    new_nonce = Nonce(id=nonce, timestamp=time)
    session.add(new_nonce)
    session.commit()
    return nonce 
Example 21
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            link_props = {}
            class_title = self.doc.parsed_classes[class_]["class"].title
            dummy_obj = gen_dummy_object(class_title, self.doc)
            for supportedProp in self.doc.parsed_classes[class_]['class'].supportedProperty:
                if isinstance(supportedProp.prop, HydraLink):
                    class_name = supportedProp.prop.range.replace("vocab:", "")
                    for collection_path in self.doc.collections:
                        coll_class = self.doc.collections[
                            collection_path]['collection'].class_.title
                        if class_name == coll_class:
                            id_ = str(uuid.uuid4())
                            crud.insert(
                                gen_dummy_object(class_name, self.doc),
                                id_=id_,
                                session=self.session)
                            link_props[supportedProp.title] = id_
                            dummy_obj[supportedProp.title] = "{}/{}/{}".format(
                                self.API_NAME, collection_path, id_)
            crud.insert(
                dummy_obj,
                id_=str(
                    uuid.uuid4()),
                link_props=link_props,
                session=self.session)
            # If it's a collection class then add an extra object so
            # we can test pagination thoroughly.
            if class_ in self.doc.collections:
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session) 
Example 22
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_get(self):
        """Test CRUD get."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        response = crud.insert(object_=object_, id_=id_, session=self.session)
        object_ = crud.get(id_=id_, type_=object_[
                           "@type"], session=self.session, api_name="api")
        assert isinstance(response, str)
        assert object_["@id"].split("/")[-1] == id_ 
Example 23
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_get_for_nested_obj(self):
        """Test get operation for object that can contain other objects."""
        for class_ in self.doc_collection_classes:
            for prop in self.doc.parsed_classes[class_]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or "vocab:" in prop.prop:
                    link_props = {}
                    dummy_obj = gen_dummy_object(class_, self.doc)
                    if isinstance(prop.prop, HydraLink):
                        nested_class = prop.prop.range.replace("vocab:", "")
                        for collection_path in self.doc.collections:
                            coll_class = self.doc.collections[
                                collection_path]['collection'].class_.title
                            if nested_class == coll_class:
                                id_ = str(uuid.uuid4())
                                crud.insert(
                                    gen_dummy_object(nested_class, self.doc),
                                    id_=id_,
                                    session=self.session)
                                link_props[prop.title] = id_
                                dummy_obj[prop.title] = "{}/{}/{}".format(
                                    self.API_NAME, collection_path, id_)
                    else:
                        nested_class = prop.prop.replace("vocab:", "")
                    obj_id = str(uuid.uuid4())
                    response = crud.insert(object_=dummy_obj, id_=obj_id,
                                           link_props=link_props, session=self.session)
                    object_ = crud.get(id_=obj_id, type_=class_, session=self.session,
                                       api_name="api")
                    assert prop.title in object_
                    nested_obj_id = object_[prop.title]
                    nested_obj = crud.get(id_=nested_obj_id, type_=nested_class,
                                          session=self.session, api_name="api")
                    assert nested_obj["@id"].split("/")[-1] == nested_obj_id
                    break 
Example 24
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_get_type(self):
        """Test CRUD get when wrong/undefined class is given."""
        id_ = str(uuid.uuid4())
        type_ = "otherClass"
        response_code = None
        try:
            get_response = crud.get(
                id_=id_, type_=type_, session=self.session, api_name="api")
        except Exception as e:
            error = e.get_HTTP()
        assert 400 == error.code 
Example 25
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_insert_type(self):
        """Test CRUD insert when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        object_["@type"] = "otherClass"
        response_code = None
        try:
            insert_response = crud.insert(
                object_=object_, id_=id_, session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 26
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_insert_used_id(self):
        """Test CRUD insert when used ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            insert_response = crud.insert(
                object_=object_, id_=id_, session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 27
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        for class_ in self.doc.parsed_classes:
            if class_ not in self.doc.collections:
                class_type = self.doc.parsed_classes[class_]['class'].title
                dummy_obj = gen_dummy_object(class_type, self.doc)
                crud.insert(
                    dummy_obj,
                    id_=str(
                        uuid.uuid4()),
                    session=self.session) 
Example 28
Project: drydock   Author: airshipit   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.log_level = 'ERROR'
        self.user = None  # Username
        self.user_id = None  # User ID (UUID)
        self.user_domain_id = None  # Domain owning user
        self.roles = []
        self.project_id = None
        self.project_domain_id = None  # Domain owning project
        self.is_admin_project = False
        self.authenticated = False
        self.request_id = str(uuid.uuid4())
        self.external_marker = ''
        self.policy_engine = None
        self.end_user = None  # Initial User 
Example 29
Project: drydock   Author: airshipit   File: task.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 action=None,
                 design_ref=None,
                 parent_task_id=None,
                 node_filter=None,
                 context=None,
                 statemgr=None,
                 retry=0):
        self.statemgr = statemgr

        self.task_id = uuid.uuid4()
        self.status = hd_fields.TaskStatus.Requested
        self.subtask_id_list = []
        self.result = TaskStatus()
        self.action = action or hd_fields.OrchestratorAction.Noop
        self.design_ref = design_ref
        self.retry = retry
        self.parent_task_id = parent_task_id
        self.created = datetime.utcnow()
        self.node_filter = copy.deepcopy(node_filter)
        self.created_by = None
        self.updated = None
        self.terminated = None
        self.terminated_by = None
        self.request_context = context
        self.terminate = False
        self.logger = logging.getLogger("drydock")

        if context is not None:
            self.created_by = context.user 
Example 30
Project: drydock   Author: airshipit   File: site.py    License: Apache License 2.0 5 votes vote down vote up
def assign_id(self):
        self.id = uuid.uuid4()
        return self.id

    # SiteDesign Keyed by id