当前位置: 首页>>代码示例>>Python>>正文


Python yaml.CSafeLoader方法代码示例

本文整理汇总了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() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:20,代码来源:graphics.py

示例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() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:26,代码来源:groups.py

示例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() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:21,代码来源:dogmaAttributeCategories.py

示例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() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:21,代码来源:bsdTables.py

示例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 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:27,代码来源:utils.py

示例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") 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:23,代码来源:__init__.py

示例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]) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:pyyaml.py

示例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() 
开发者ID:keylime,项目名称:keylime,代码行数:23,代码来源:ca_util.py

示例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 
开发者ID:keylime,项目名称:keylime,代码行数:26,代码来源:provider_vtpm_add.py

示例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) 
开发者ID:UCL-INGI,项目名称:INGInious,代码行数:23,代码来源:custom_yaml.py

示例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) 
开发者ID:RedHatInsights,项目名称:insights-core,代码行数:21,代码来源:__init__.py

示例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 
开发者ID:sayoun,项目名称:pyvac,代码行数:20,代码来源:config.py

示例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 
开发者ID:mlflow,项目名称:mlflow,代码行数:23,代码来源:file_utils.py

示例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) 
开发者ID:olofk,项目名称:fusesoc,代码行数:5,代码来源:utils.py

示例15: yaml_read

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CSafeLoader [as 别名]
def yaml_read(data):
    return yaml.load(data, Loader=YamlLoader) 
开发者ID:olofk,项目名称:fusesoc,代码行数:4,代码来源:utils.py


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