本文整理汇总了Python中utils.json_dump函数的典型用法代码示例。如果您正苦于以下问题:Python json_dump函数的具体用法?Python json_dump怎么用?Python json_dump使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_dump函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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)
示例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)
示例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)
示例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,
)
示例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)
示例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)
示例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
示例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)
示例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))
示例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)
示例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
示例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)
示例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)