从字符串引号中的字节对象获取字节对象

Get bytes object from bytes object in string quotes

我想在我的应用程序中使用 Whoosh,并遵循了 2011 年编写的教程 here

当我尝试解开这个块中的数据时:

def results_to_instances(request, results):
    instances = []
    for r in results:
        cls = pickle.loads('{0}'.format(r.get('cls')))
        id = r.get('id')
        instance = request.db.query(cls).get(id)
        instances.append(instance)
    return instances

我从 pickle.loads() 命令中得到一个错误:

TypeError: 'str' does not support the buffer interface

当我检查什么'{0}'.format(r.get('cls')) returns时,它是str类型,但值是"b'foo'"

如何从字符串中获取字节对象?编码只是 returns b"b'foo'".

在此块中腌制值:

def first_index(self, writer):
        oid = u'{0}'.format(self.id)
        cls = u'{0}'.format(pickle.dumps(self.__class__))
        attributes = []
        for attr in self.__whoosh_value__.split(','):
            if getattr(self, attr) is not None:
                attributes.append(str(getattr(self, attr)))
        value = u' '.join(attributes)
        writer.add_document(id=oid, cls=cls, value=value)

所以如果有办法从根部修复就更好了

只需使用r.get('cls')。将它包装在 '{0}'.format() 中首先会使 bytes 变成 str,这根本不是您想要的。当你包装 pickle.dumps 时也是如此(立即将有用的 bytes it returns 转换为无用的格式化版本)。基本上,您对 '{0}'.format() 的所有使用都没有意义,因为当您尝试使用原始数据时,它们会产生 str