• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.json_dump函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中utils.json_dump函数的典型用法代码示例。如果您正苦于以下问题:Python json_dump函数的具体用法?Python json_dump怎么用?Python json_dump使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了json_dump函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: trylock

def trylock(path, excl, key_path):
    with lockfile.LockFile(path):
        # Prune invalid users
        if os.path.exists(_lock_path(path)):
            with open(_lock_path(path)) as f:
                lock_obj = json.load(f)
        else:
            lock_obj = {'excl': False, 'users': {}}
        for other_key_path in lock_obj['users'].copy():
            if not os.path.isfile(other_key_path):
                del lock_obj['users'][other_key_path]
                continue
            with open(other_key_path) as f:
                key = f.read()
            if key != lock_obj['users'][other_key_path]:
                del lock_obj['users'][other_key_path]

        if (
            (excl and len(lock_obj['users']) != 0)
            or (not excl and lock_obj['excl'] and len(lock_obj['users']) != 0)
        ):
            success = False
        else:
            lock_obj['excl'] = excl
            with open(key_path) as f:
                lock_obj['users'][key_path] = f.read()
            success = True

        # Update lock object file
        with open(_lock_path(path), 'w') as f:
            utils.json_dump(lock_obj, f)

        return success
开发者ID:DavideD,项目名称:lago,代码行数:33,代码来源:dirlock.py


示例2: mark_used

    def mark_used(self, temp_ver, key_path):
        """
        Adds or updates the user entry in the user access log for the given
        template version

        Args:
            temp_ver (TemplateVersion): template version to add the entry for
            key_path (str): Path to the prefix uuid file to set the mark for
        """
        dest = self.get_path(temp_ver)

        with lockfile.LockFile(dest):
            with open('%s.users' % dest) as f:
                users = json.load(f)

            updated_users = {}
            for path, key in users['users'].items():
                try:
                    with open(path) as f:
                        if key == f.read():
                            updated_users[path] = key
                except OSError:
                    pass
                except IOError:
                    pass

            with open(key_path) as f:
                updated_users[key_path] = f.read()
            users['users'] = updated_users
            users['last_access'] = int(time.time())
            with open('%s.users' % dest, 'w') as f:
                utils.json_dump(users, f)
开发者ID:lago-project,项目名称:lago,代码行数:32,代码来源:templates.py


示例3: unlock

def unlock(path, key_path):
    with lockfile.LockFile(path):
        with open(_lock_path(path)) as f:
            lock_obj = json.load(f)
        del lock_obj['users'][key_path]
        with open(_lock_path(path), 'w') as f:
            utils.json_dump(lock_obj, f)
开发者ID:DavideD,项目名称:lago,代码行数:7,代码来源:dirlock.py


示例4: _save_metadata

 def _save_metadata(self):
     """
     Write this prefix metadata to disk
     Returns:
         None
     """
     with open(self.paths.metadata(), 'w') as metadata_fd:
         utils.json_dump(self._get_metadata(), metadata_fd)
开发者ID:irosenzw,项目名称:lago,代码行数:8,代码来源:prefix.py


示例5: download

    def download(self, temp_ver, store_metadata=True):
        """
        Retrieve the given template version

        Args:
            temp_ver (TemplateVersion): template version to retrieve
            store_metadata (bool): If set to ``False``, will not refresh the
                local metadata with the retrieved one

        Returns:
            None
        """
        dest = self._prefixed(temp_ver.name)
        temp_dest = '%s.tmp' % dest

        with lockfile.LockFile(dest):
            # Image was downloaded while we were waiting
            if os.path.exists(dest):
                return

            temp_ver.download(temp_dest)
            if store_metadata:
                with open('%s.metadata' % dest, 'w') as f:
                    utils.json_dump(temp_ver.get_metadata(), f)

            sha1 = hashlib.sha1()
            with open(temp_dest) as f:
                while True:
                    chunk = f.read(65536)
                    if not chunk:
                        break
                    sha1.update(chunk)
            if temp_ver.get_hash() != sha1.hexdigest():
                raise RuntimeError(
                    'Image %s does not match the expected hash %s' % (
                        temp_ver.name,
                        sha1.hexdigest(),
                    )
                )

            with open('%s.hash' % dest, 'w') as f:
                f.write(sha1.hexdigest())

            with log_utils.LogTask('Convert image', logger=LOGGER):
                utils.run_command(
                    [
                        'qemu-img',
                        'convert',
                        '-O',
                        'raw',
                        temp_dest,
                        dest,
                    ],
                )

            os.unlink(temp_dest)

            self._init_users(temp_ver)
开发者ID:lago-project,项目名称:lago,代码行数:58,代码来源:templates.py


示例6: _init_users

 def _init_users(self, temp_ver):
     with open('%s.users' % self.get_path(temp_ver), 'w') as f:
         utils.json_dump(
             {
                 'users': {},
                 'last_access': int(time.time()),
             },
             f,
         )
开发者ID:tlitovsk,项目名称:ovirt-testing-framework,代码行数:9,代码来源:templates.py


示例7: save

    def save(self):
        for net in self._nets.values():
            net.save()
        for vm in self._vms.values():
            vm.save()

        spec = {
            'nets': self._nets.keys(),
            'vms': self._vms.keys(),
        }

        with open(self.virt_path('env'), 'w') as f:
            utils.json_dump(spec, f)
开发者ID:oourfali,项目名称:ovirt-testing-framework,代码行数:13,代码来源:virt.py


示例8: save

    def save(self):
        with LogTask("Save nets"):
            for net in self._nets.values():
                net.save()

        with LogTask("Save VMs"):
            for vm in self._vms.values():
                vm.save()

        spec = {"nets": self._nets.keys(), "vms": self._vms.keys()}

        with LogTask("Save env"):
            with open(self.virt_path("env"), "w") as f:
                utils.json_dump(spec, f)
开发者ID:DavideD,项目名称:lago-1,代码行数:14,代码来源:virt.py


示例9: can_close

 def can_close(self):
     # Let everyone know we are leaving...
     if hasattr(self, '_bounce_window') and \
        self._bounce_window.we_are_sharing():
         self._playing = False
         self.send_event('l', {"data": (json_dump([self.nick]))})
     return True
开发者ID:leonardcj,项目名称:fractionbounce,代码行数:7,代码来源:FractionBounceActivity.py


示例10: _take_lease

def _take_lease(path, uuid_path):
    """
    Persist to the given leases path the prefix uuid that's in the uuid path
    passed

    Args:
        path (str): Path to the leases file
        uuid_path (str): Path to the prefix uuid

    Returns:
        None
    """
    with open(uuid_path) as f:
        uuid = f.read()
    with open(path, 'w') as f:
        utils.json_dump((uuid_path, uuid), f)
开发者ID:Apekhsha,项目名称:lago,代码行数:16,代码来源:subnet_lease.py


示例11: _new_joiner

 def _new_joiner(self, payload):
     ''' Someone has joined; sharer adds them to the buddy list. '''
     [nick, colors] = json_load(payload)
     self.status.set_label(nick + ' ' + _('has joined.'))
     self._append_player(nick, colors)
     if self.initiating:
         payload = json_dump([self._game.buddies, self._player_colors])
         self.send_event('b|%s' % (payload))
开发者ID:erilyth,项目名称:paths,代码行数:8,代码来源:PathsActivity.py


示例12: download

    def download(self, temp_ver, store_metadata=True):
        dest = self._prefixed(temp_ver.name)
        temp_dest = '%s.tmp' % dest

        with lockfile.LockFile(dest):
            # Image was downloaded while we were waiting
            if os.path.exists(dest):
                return

            temp_ver.download(temp_dest)
            if store_metadata:
                with open('%s.metadata' % dest, 'w') as f:
                    utils.json_dump(temp_ver.get_metadata(), f)

            sha1 = hashlib.sha1()
            with open(temp_dest) as f:
                while True:
                    chunk = f.read(65536)
                    if not chunk:
                        break
                    sha1.update(chunk)
            if temp_ver.get_hash() != sha1.hexdigest():
                raise RuntimeError(
                    'Image %s does not match the expected hash %s' % (
                        temp_ver.name,
                        sha1.hexdigest(),
                    )
                )

            with open('%s.hash' % dest, 'w') as f:
                f.write(sha1.hexdigest())

            utils.run_command(
                [
                    'qemu-img',
                    'convert',
                    '-O', 'raw',
                    temp_dest,
                    dest,
                ],
            )

            os.unlink(temp_dest)

            self._init_users(temp_ver)
开发者ID:tlitovsk,项目名称:ovirt-testing-framework,代码行数:45,代码来源:templates.py


示例13: trylock

def trylock(path, excl, key_path):
    """
    Tries once to get a lock to the given dir

    Args:
        path(str): path to the directory to lock
        excl(bool): If the lock should be exclusive
        key_path(str): path to the file that contains the uid to use when
            locking

    Returns:
        bool: True if it did get a lock, False otherwise
    """
    with lockfile.LockFile(path):
        # Prune invalid users
        if os.path.exists(_lock_path(path)):
            with open(_lock_path(path)) as f:
                lock_obj = json.load(f)
        else:
            lock_obj = {'excl': False, 'users': {}}
        for other_key_path in lock_obj['users'].copy():
            if not os.path.isfile(other_key_path):
                del lock_obj['users'][other_key_path]
                continue
            with open(other_key_path) as f:
                key = f.read()
            if key != lock_obj['users'][other_key_path]:
                del lock_obj['users'][other_key_path]

        if (
            (excl and len(lock_obj['users']) != 0)
            or (not excl and lock_obj['excl'] and len(lock_obj['users']) != 0)
        ):
            success = False
        else:
            lock_obj['excl'] = excl
            with open(key_path) as f:
                lock_obj['users'][key_path] = f.read()
            success = True

        # Update lock object file
        with open(_lock_path(path), 'w') as f:
            utils.json_dump(lock_obj, f)

        return success
开发者ID:Apekhsha,项目名称:lago,代码行数:45,代码来源:dirlock.py


示例14: unlock

def unlock(path, key_path):
    """
    Removes the lock of the uid in the given key file

    Args:
        path(str): Path of the directory to lock
        key_path(str): path to the file that contains the uid to remove the
            lock of

    Returns:
        None
    """
    with lockfile.LockFile(path):
        with open(_lock_path(path)) as f:
            lock_obj = json.load(f)
        del lock_obj['users'][key_path]
        with open(_lock_path(path), 'w') as f:
            utils.json_dump(lock_obj, f)
开发者ID:Apekhsha,项目名称:lago,代码行数:18,代码来源:dirlock.py


示例15: serialize

 def serialize(self):
     ''' Serialize the grid for passing to share and saving '''
     grid = []
     for i in range(ROW * COL):
         if self.grid[i] is not None:
             grid.append([self.grid[i].number, self.grid[i].orientation])
         else:
             grid.append([None, None])
     return json_dump(grid)
开发者ID:leonardcj,项目名称:paths,代码行数:9,代码来源:grid.py


示例16: _buddy_left

 def _buddy_left(self, payload):
     [nick] = json_load(payload)
     self._label.set_label(nick + ' ' + _('has left.'))
     if self.initiating:
         self._remove_player(nick)
         payload = json_dump([self._bounce_window.buddies,
                              self._player_colors])
         self.send_event('b', {"data": payload})
         # Restart from sharer's turn
         self._bounce_window.its_my_turn()
开发者ID:leonardcj,项目名称:fractionbounce,代码行数:10,代码来源:FractionBounceActivity.py


示例17: _init_users

    def _init_users(self, temp_ver):
        """
        Initializes the user access registry

        Args:
            temp_ver (TemplateVersion): template version to update registry
                for

        Returns:
            None
        """
        with open('%s.users' % self.get_path(temp_ver), 'w') as f:
            utils.json_dump(
                {
                    'users': {},
                    'last_access': int(time.time()),
                },
                f,
            )
开发者ID:lago-project,项目名称:lago,代码行数:19,代码来源:templates.py


示例18: _new_joiner

 def _new_joiner(self, payload):
     ''' Someone has joined; sharer adds them to the buddy list. '''
     [nick, colors] = json_load(payload)
     self._label.set_label(nick + ' ' + _('has joined.'))
     if self.initiating:
         self._append_player(nick, colors)
         payload = json_dump([self._bounce_window.buddies,
                              self._player_colors])
         self.send_event('b', {"data": payload})
         if self._bounce_window.count == 0:  # Haven't started yet...
             self._bounce_window.its_my_turn()
开发者ID:leonardcj,项目名称:fractionbounce,代码行数:11,代码来源:FractionBounceActivity.py


示例19: serialize

 def serialize(self, buddy=None):
     ''' Serialize the hand for passing to share and saving '''
     if buddy == None:
         hand = []
     else:
         hand = [buddy]
     for i in range(COL):
         if self.hand[i] is not None:
             hand.append(self.hand[i].number)
         else:
             hand.append(None)
     return json_dump(hand)
开发者ID:erilyth,项目名称:paths,代码行数:12,代码来源:hand.py


示例20: mark_used

    def mark_used(self, temp_ver, key_path):
        dest = self.get_path(temp_ver)

        with lockfile.LockFile(dest):
            with open('%s.users' % dest) as f:
                users = json.load(f)

            updated_users = {}
            for path, key in users['users'].items():
                try:
                    with open(path) as f:
                        if key == f.read():
                            updated_users[path] = key
                except OSError:
                    pass
                except IOError:
                    pass

            with open(key_path) as f:
                updated_users[key_path] = f.read()
            users['users'] = updated_users
            users['last_access'] = int(time.time())
            with open('%s.users' % dest, 'w') as f:
                utils.json_dump(users, f)
开发者ID:tlitovsk,项目名称:ovirt-testing-framework,代码行数:24,代码来源:templates.py



注:本文中的utils.json_dump函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.json_encode函数代码示例发布时间:2022-05-26
下一篇:
Python utils.join_path函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap