简体   繁体   English

如何将受Perl祝福的对象转换为Python可以读取的YAML

[英]How to turn Perl blessed objects into YAML that Python can read

We have a REST web service written in Perl Dancer. 我们有一个用Perl Dancer编写的REST Web服务。 It returns perl data structures in YAML format and also takes in parameters in YAML format - it is supposed to work with some other teams who query it using Python. 它以YAML格式返回perl数据结构,并以YAML格式接收参数-应该与其他一些使用Python查询它的团队一起使用。

Here's the problem -- if I'm passing back just a regular old perl hash by Dancer's serialization everything works completely fine. 这就是问题所在-如果我通过Dancer的序列化仅回传一个常规的旧Perl哈希,则一切工作都很好。 JSON, YAML, XML... they all do the job. JSON,YAML,XML ...它们都能完成任务。

HOWEVER , sometimes we need to pass Perl objects back that the Python can later pass back in as a parameter to help with unnecessary loading, etc. I played around and found that YAML is the only one that works with Perl's blessed objects in Dancer. 但是有时我们需要将Perl对象传递回去 ,Python以后可以将其作为参数传递回去,以帮助进行不必要的加载等。我玩弄了一下,发现YAML是唯一与Dancer中Perl的祝福对象一起使用的对象。

The problem is that Python's YAML can't parse through the YAMLs of the Perl objects (whereas it can handle regular old perl hash YAMLs without an issue). 问题在于,Python的YAML无法解析Perl对象的YAML(而它可以毫无问题地处理常规的旧Perl哈希YAML)。

The perl objects start out like this in YAML: Perl对象在YAML中以如下方式开始:

First one: 第一:

--- &1 !!perl/hash:Sequencing_API

Second: 第二:

--- !!perl/hash:SDB::DBIO

It errors out like this. 这样会出错。

yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:perl/hash:SDB::DBIO'

The regular files seem to get passed through like this: 常规文件似乎像这样通过:

--- fields: library:

It seems like the extra stuff after --- are causing the issues. 似乎---之后的多余内容导致了问题。 What can I do to address this? 我该怎么办? Or am I trying to do too much by passing around Perl objects? 还是我试图通过传递Perl对象做太多事情?

the short answer is 简短的答案是

!! is yaml shorthand for tag:yaml.org,2002: ... as such !!perl/hash is really tag:yaml.org,2002:perl/hash tag:yaml.org,2002: yaml简写tag:yaml.org,2002: ...就这样!!perl/hash实际上是tag:yaml.org,2002:perl/hash

now you need to tell python yaml how to deal with this type 现在您需要告诉python yaml如何处理这种类型

so you add a constructor for it as follows 因此,您可以为其添加一个构造函数,如下所示

import yaml


def construct_perl_object(loader, node):
    print "S:",suffix,"N:",node
    return loader.construct_yaml_node(node)#this is likely wrong ....



yaml.add_multi_constructor(u"tag:yaml.org,2002:perl/hash:SDB::DBIO", construct_perl_object)
yaml.load(yaml_string)

or maybe just parse it out or return None maybe ... its hard to test with just that line ... but that may be what you are looking for 或只是解析出来或不返回None……仅用那条线很难测试...但这可能就是您想要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM