Python uuid.uuid4() Examples

The following are 30 code examples of uuid.uuid4(). 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: utils.py    From ciocheck with 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 #2
Source File: test_auth_middleware.py    From drydock with 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 #3
Source File: test_maasdriver_network.py    From drydock with 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 #4
Source File: test_postgres_builddata.py    From drydock with 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 #5
Source File: test_postgres_builddata.py    From drydock with 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 #6
Source File: workflow3.py    From wechat-alfred-workflow with 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 #7
Source File: test_crud.py    From hydrus with 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 #8
Source File: test_crud.py    From hydrus with 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 #9
Source File: test_crud.py    From hydrus with 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 #10
Source File: test_crud.py    From hydrus with 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 #11
Source File: test_crud.py    From hydrus with 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 #12
Source File: database.py    From pgrepup with 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 #13
Source File: calendar_token.py    From everyclass-server with 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 #14
Source File: test_app.py    From hydrus with 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 #15
Source File: test_app.py    From hydrus with 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 #16
Source File: test_app.py    From hydrus with 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 #17
Source File: verification_request.py    From everyclass-server with 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 #18
Source File: tdata.py    From MPContribs with 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 #19
Source File: utils.py    From iris with MIT License 5 votes vote down vote up
def get_uuid():
    uuid.uuid4() 
Example #20
Source File: storage.py    From invana-bot with MIT License 5 votes vote down vote up
def generate_random_id():
    return str(uuid.uuid4().hex) 
Example #21
Source File: point.py    From tfont with Apache License 2.0 5 votes vote down vote up
def id(self):
        extraData = self.extraData
        try:
            return extraData["id"]
        except KeyError:
            extraData["id"] = id_ = str(uuid4())
            return id_ 
Example #22
Source File: shared.py    From video2commons with GNU General Public License v3.0 5 votes vote down vote up
def generate_csrf_token():
    """Generate a CSRF token."""
    if '_csrf_token' not in session:
        session['_csrf_token'] = str(uuid4())
    return session['_csrf_token'] 
Example #23
Source File: api_requestor.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _build_headers(cls, api_key=None, method="get", **kwargs):

        # The SDK's user agent info
        user_agent = _UA

        # (Optionally) the client's user agent info
        app_str = ""
        if codepost.app_info:
            app_str = cls._format_app_info(**codepost.app_info)
            user_agent += " " + app_str

        # Diagnostic information
        diag = {
            "sdk": _CODEPOST_SDK_VERSION,
            "lang": "python",
            "publisher": "codepost",
            "lang_version": _PY_VERSION,
            "platform": _platform.platform(),
            "uname": _platform.uname(),
            "app": app_str,
        }

        headers = {
            "Authorization": "Token {}".format(api_key),
            "User-Agent": user_agent,
            "X-codePost-SDK-User-Agent": _json.dumps(diag)
        }

        if method.upper() in ["POST", "PATCH"] and not "Content-Type" in headers:
            headers["Content-Type"] = "application/json"

        if method.upper() == "POST":
            headers.setdefault("Idempotency-Key", str(_uuid.uuid4()))

        return headers 
Example #24
Source File: loader.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_module(self, doc, message, name=None, origin="<string>"):
        if name is None:
            uid = "__extmod_" + str(uuid.uuid4())
        else:
            uid = name.replace("%", "%%").replace(".", "%d")
        module_name = "friendly-telegram.modules." + uid
        try:
            module = importlib.util.module_from_spec(ModuleSpec(module_name, StringLoader(doc, origin), origin=origin))
            sys.modules[module_name] = module
            module.borg = uniborg.UniborgClient(module_name)
            module._ = _  # noqa: F821
            module.__spec__.loader.exec_module(module)
        except Exception:  # That's okay because it might try to exit or something, who knows.
            logger.exception("Loading external module failed.")
            if message is not None:
                await utils.answer(message, self.strings["load_failed"])
            return False
        if "register" not in vars(module):
            if message is not None:
                await utils.answer(message, self.strings["load_failed"])
            logging.error("Module does not have register(), it has " + repr(vars(module)))
            return False
        try:
            try:
                module.register(self.register_and_configure, module_name)
            except TypeError:
                module.register(self.register_and_configure)
            await self._pending_setup.pop()
        except Exception:
            logger.exception("Module threw")
            if message is not None:
                await utils.answer(message, self.strings["load_failed"])
            return False
        if message is not None:
            await utils.answer(message, self.strings["loaded"])
        return True 
Example #25
Source File: updater.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def prerestart_common(self, message):
        logger.debug("Self-update. " + sys.executable + " -m " + utils.get_base_dir())
        check = str(uuid.uuid4())
        await self._db.set(__name__, "selfupdatecheck", check)
        await asyncio.sleep(3)
        if self._db.get(__name__, "selfupdatecheck", "") != check:
            raise ValueError("An update is already in progress!")
        self._db.set(__name__, "selfupdatechat", utils.get_chat_id(message))
        await self._db.set(__name__, "selfupdatemsg", message.id) 
Example #26
Source File: entity.py    From python-clean-architecture with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__(generator=uuid4) 
Example #27
Source File: hooks.py    From pinax-documents with MIT License 5 votes vote down vote up
def file_upload_to(self, instance, filename):
        """
        Callable passed to the FileField's upload_to kwarg on Document.file
        """
        ext = filename.split(".")[-1]
        filename = f"{uuid.uuid4()}.{ext}"
        return os.path.join("document", filename) 
Example #28
Source File: worker.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT):
    """Runs docker command and enforces time limit.

    Args:
      cmd: list with the command line arguments which are passed to docker
        binary after run
      time_limit: time limit, in seconds. Negative value means no limit.

    Returns:
      how long it took to run submission in seconds

    Raises:
      WorkerError: if error occurred during execution of the submission
    """
    if time_limit < 0:
      return self.run_without_time_limit(cmd)
    container_name = str(uuid.uuid4())
    cmd = [DOCKER_BINARY, 'run', DOCKER_NVIDIA_RUNTIME,
           '--detach', '--name', container_name] + cmd
    logging.info('Docker command: %s', ' '.join(cmd))
    logging.info('Time limit %d seconds', time_limit)
    retval = subprocess.call(cmd)
    start_time = time.time()
    elapsed_time_sec = 0
    while is_docker_still_running(container_name):
      elapsed_time_sec = long(time.time() - start_time)
      if elapsed_time_sec < time_limit:
        time.sleep(1)
      else:
        kill_docker_container(container_name)
        logging.warning('Submission was killed because run out of time')
    logging.info('Elapsed time of submission: %d', elapsed_time_sec)
    logging.info('Docker retval: %d', retval)
    if retval != 0:
      logging.warning('Docker returned non-zero retval: %d', retval)
      raise WorkerError('Docker returned non-zero retval ' + str(retval))
    return elapsed_time_sec 
Example #29
Source File: utils.py    From ciocheck with MIT License 5 votes vote down vote up
def atomic_replace(path, contents, encoding):
    """Try to do an atomic replace."""
    tmp = "{0}tmp-{1}".format(path, str(uuid.uuid4()))
    try:
        with codecs.open(tmp, 'w', encoding) as file_obj:
            file_obj.write(contents)
            file_obj.flush()
            file_obj.close()
        _rename_over_existing(tmp, path)
    finally:
        try:
            os.remove(tmp)
        except (IOError, OSError):
            pass 
Example #30
Source File: gdata.py    From MPContribs with MIT License 5 votes vote down vote up
def to_mimebundle(self, fig):
        fig_dict = validate_coerce_fig_to_dict(fig, True)
        divid = str(uuid.uuid4())
        data = fig_dict.get("data", [])
        jdata = json.dumps(data, cls=PlotlyJSONEncoder, sort_keys=True)
        layout = fig_dict.get("layout", {})
        jlayout = json.dumps(layout, cls=PlotlyJSONEncoder, sort_keys=True)
        config = _get_jconfig(None)
        config.setdefault("responsive", True)
        jconfig = json.dumps(config)
        script = f'render_plot({{divid: "{divid}", layout: {jlayout}, config: {jconfig}'
        script += f', tid: "{self.tid}", data: {jdata}}})'
        html = f'<div><div id="{divid}"></div>'
        html += f'<script type="text/javascript">{script};</script></div>'
        return {"text/html": html}