本文整理匯總了Python中yaml.CSafeLoader方法的典型用法代碼示例。如果您正苦於以下問題:Python yaml.CSafeLoader方法的具體用法?Python yaml.CSafeLoader怎麽用?Python yaml.CSafeLoader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類yaml
的用法示例。
在下文中一共展示了yaml.CSafeLoader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: importyaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def importyaml(connection,metadata,sourcePath):
eveGraphics = Table('eveGraphics',metadata)
print "Importing Graphics"
print "opening Yaml"
with open(os.path.join(sourcePath,'fsd','graphicIDs.yaml'),'r') as yamlstream:
print "importing"
trans = connection.begin()
graphics=load(yamlstream,Loader=SafeLoader)
print "Yaml Processed into memory"
for graphic in graphics:
connection.execute(eveGraphics.insert(),
graphicID=graphic,
sofFactionName=graphics[graphic].get('sofFactionName',''),
graphicFile=graphics[graphic].get('graphicFile',''),
sofHullName=graphics[graphic].get('sofHullName',''),
sofRaceName=graphics[graphic].get('sofRaceName',''),
description=graphics[graphic].get('description',''))
trans.commit()
示例2: importyaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def importyaml(connection,metadata,sourcePath,language='en'):
invGroups = Table('invGroups',metadata)
trnTranslations = Table('trnTranslations',metadata)
print "Importing Groups"
print "opening Yaml"
with open(os.path.join(sourcePath,'fsd','groupIDs.yaml'),'r') as yamlstream:
trans = connection.begin()
groupids=load(yamlstream,Loader=SafeLoader)
print "Yaml Processed into memory"
for groupid in groupids:
connection.execute(invGroups.insert(),
groupID=groupid,
categoryID=groupids[groupid].get('categoryID',0),
groupName=groupids[groupid].get('name',{}).get(language,'').decode('utf-8'),
iconID=groupids[groupid].get('iconID'),
useBasePrice=groupids[groupid].get('useBasePrice'),
anchored=groupids[groupid].get('anchored',0),
anchorable=groupids[groupid].get('anchorable',0),
fittableNonSingleton=groupids[groupid].get('fittableNonSingleton',0),
published=groupids[groupid].get('published',0))
if (groupids[groupid].has_key('name')):
for lang in groupids[groupid]['name']:
connection.execute(trnTranslations.insert(),tcID=7,keyID=groupid,languageID=lang,text=groupids[groupid]['name'][lang].decode('utf-8'));
trans.commit()
示例3: importyaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def importyaml(connection,metadata,sourcePath,language='en'):
print "Importing dogma attribute categories"
dgmAttributeCategories = Table('dgmAttributeCategories',metadata)
print "opening Yaml"
trans = connection.begin()
with open(os.path.join(sourcePath,'fsd','dogmaAttributeCategories.yaml'),'r') as yamlstream:
print "importing"
dogmaAttributeCategories=load(yamlstream,Loader=SafeLoader)
print "Yaml Processed into memory"
for dogmaAttributeCategoryID in dogmaAttributeCategories:
attribute = dogmaAttributeCategories[dogmaAttributeCategoryID]
connection.execute(dgmAttributeCategories.insert(),
categoryID=dogmaAttributeCategoryID,
categoryName=attribute['name'],
categoryDescription=attribute['description']
)
trans.commit()
示例4: importyaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def importyaml(connection,metadata,sourcePath):
print "Importing BSD Tables"
files=glob.glob(os.path.join(sourcePath,'bsd','*.yaml'))
for file in files:
head, tail = os.path.split(file)
tablename=tail.split('.')[0]
print tablename
tablevar = Table(tablename,metadata)
print "Importing {}".format(file)
print "Opening Yaml"
trans = connection.begin()
with open(file,'r') as yamlstream:
rows=load(yamlstream,Loader=SafeLoader)
print "Yaml Processed into memory"
for row in rows:
connection.execute(tablevar.insert().values(row))
trans.commit()
示例5: make_loader
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def make_loader(*tags_to_remove: str) -> Type[yaml.SafeLoader]:
"""Create a YAML loader, that doesn't parse specific tokens into Python objects."""
cls: Type[yaml.SafeLoader] = type("YAMLLoader", (SafeLoader,), {})
cls.yaml_implicit_resolvers = {
key: [(tag, regexp) for tag, regexp in mapping if tag not in tags_to_remove]
for key, mapping in cls.yaml_implicit_resolvers.copy().items()
}
# Fix pyyaml scientific notation parse bug
# See PR: https://github.com/yaml/pyyaml/pull/174 for upstream fix
cls.add_implicit_resolver( # type: ignore
"tag:yaml.org,2002:float",
re.compile(
r"""^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+]?[0-9]+)?
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
|\.[0-9_]+(?:[eE][-+]?[0-9]+)?
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
|[-+]?\.(?:inf|Inf|INF)
|\.(?:nan|NaN|NAN))$""",
re.X,
),
list("-+0123456789."),
)
return cls
示例6: replay
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def replay(
cassette_path: str,
id_: Optional[str],
status: Optional[str] = None,
uri: Optional[str] = None,
method: Optional[str] = None,
) -> None:
"""Replay a cassette.
Cassettes in VCR-compatible format can be replayed.
For example, ones that are recorded with ``store-network-log`` option of `schemathesis run` command.
"""
click.secho(f"{bold('Replaying cassette')}: {cassette_path}")
with open(cassette_path) as fd:
cassette = yaml.load(fd, Loader=SafeLoader)
click.secho(f"{bold('Total interactions')}: {len(cassette['http_interactions'])}\n")
for replayed in cassettes.replay(cassette, id_=id_, status=status, uri=uri, method=method):
click.secho(f" {bold('ID')} : {replayed.interaction['id']}")
click.secho(f" {bold('URI')} : {replayed.interaction['request']['uri']}")
click.secho(f" {bold('Old status code')} : {replayed.interaction['response']['status']['code']}")
click.secho(f" {bold('New status code')} : {replayed.response.status_code}\n")
示例7: Deserializer
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of YAML data.
"""
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
if isinstance(stream_or_string, six.string_types):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
try:
for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options):
yield obj
except GeneratorExit:
raise
except Exception as e:
# Map to deserializer error
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
示例8: read_private
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def read_private(warn=False):
global global_password
if global_password is None:
setpassword(getpass.getpass("Please enter the password to decrypt your keystore: "))
if os.path.exists('private.yml'):
with open('private.yml','r') as f:
toread = yaml.load(f, Loader=SafeLoader)
key = crypto.kdf(global_password,toread['salt'])
try:
plain = crypto.decrypt(toread['priv'],key)
except ValueError:
raise Exception("Invalid password for keystore")
return yaml.load(plain, Loader=SafeLoader),toread['salt']
else:
if warn:
#file doesn't exist, just invent a salt
logger.warning("Private certificate data %s does not exist yet."%os.path.abspath("private.yml"))
logger.warning("Keylime will attempt to load private certificate data again when it is needed.")
return {'revoked_keys':[]},base64.b64encode(crypto.generate_random_key()).decode()
示例9: add_vtpm
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def add_vtpm(inputfile):
# read in the file
with open(inputfile,'r') as f:
group = yaml.load(f, Loader=SafeLoader)
# fetch configuration parameters
provider_reg_port = config.get('registrar', 'provider_registrar_port')
provider_reg_ip = config.get('registrar', 'provider_registrar_ip')
# request a vtpm uuid from the manager
vtpm_uuid = vtpm_manager.add_vtpm_to_group(group['uuid'])
# registrar it and get back a blob
keyblob = registrar_client.doRegisterAgent(provider_reg_ip,provider_reg_port,vtpm_uuid,group['pubekpem'],group['ekcert'],group['aikpem'])
# get the ephemeral registrar key by activating in the hardware tpm
key = base64.b64encode(vtpm_manager.activate_group(group['uuid'], keyblob))
# tell the registrar server we know the key
registrar_client.doActivateAgent(provider_reg_ip,provider_reg_port,vtpm_uuid,key)
logger.info("Registered new vTPM with UUID: %s"%(vtpm_uuid))
return vtpm_uuid
示例10: load
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def load(stream):
"""
Parse the first YAML document in a stream
and produce the corresponding Python
object. Use OrderedDicts to produce dicts.
Safe version.
"""
class OrderedLoader(SafeLoader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node))
OrderedLoader.add_constructor(
original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return original_yaml.load(stream, OrderedLoader)
示例11: parse_content
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def parse_content(self, content):
try:
if type(content) is list:
self.data = yaml.load('\n'.join(content), Loader=SafeLoader)
else:
self.data = yaml.load(content, Loader=SafeLoader)
if self.data is None:
raise SkipException("There is no data")
if not isinstance(self.data, (dict, list)):
raise ParseException("YAML didn't produce a dictionary or list.")
except SkipException as se:
tb = sys.exc_info()[2]
six.reraise(SkipException, SkipException(str(se)), tb)
except:
tb = sys.exc_info()[2]
cls = self.__class__
name = ".".join([cls.__module__, cls.__name__])
msg = "%s couldn't parse yaml." % name
six.reraise(ParseException, ParseException(msg), tb)
示例12: configure
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def configure(filename='conf/pyvac.yaml', init_celery=True, default_app=None):
with open(filename) as fdesc:
conf = yaml.load(fdesc, YAMLLoader)
if conf.get('logging'):
dictConfig(conf.get('logging'))
if init_celery:
if not default_app:
try:
from celery import current_app as default_app
except ImportError: # pragma: no cover
from celery.app import default_app
default_app.config_from_object(conf.get('celeryconfig'))
# XXX: must call loader for celery to register all the tasks
default_app.loader.import_default_modules()
return conf
示例13: read_yaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def read_yaml(root, file_name):
"""
Read data from yaml file and return as dictionary
:param root: Directory name
:param file_name: File name. Expects to have '.yaml' extension
:return: Data in yaml file as dictionary
"""
if not exists(root):
raise MissingConfigException(
"Cannot read '%s'. Parent dir '%s' does not exist." % (file_name, root))
file_path = os.path.join(root, file_name)
if not exists(file_path):
raise MissingConfigException("Yaml file '%s' does not exist." % file_path)
try:
with codecs.open(file_path, mode='r', encoding=ENCODING) as yaml_file:
return yaml.load(yaml_file, Loader=YamlSafeLoader)
except Exception as e:
raise e
示例14: yaml_fread
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def yaml_fread(filepath):
with open(filepath) as f:
return yaml.load(f, Loader=YamlLoader)
示例15: yaml_read
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CSafeLoader [as 別名]
def yaml_read(data):
return yaml.load(data, Loader=YamlLoader)