简体   繁体   English

如何在Python中序列化哈希对象

[英]How to serialize hash objects in Python

How can I serialize hash objects?, I'm using shelve to store a lot of objects. 我如何序列化哈希对象?,我正在使用货架来存储很多对象。

Hierarchy: 层次结构:

- user
    - client
    - friend

user.py: user.py:

import time
import hashlib
from localfile import localfile

class user(object):
    _id = 0
    _ip = "127.0.0.1"
    _nick = "Unnamed"
    _files = {}
    def __init__(self, ip="127.0.0.1", nick="Unnamed"):
        self._id = hashlib.sha1(str(time.time()))
        self._ip = ip
        self._nick = nick
    def add_file(self, localfile):
        self._files[localfile.hash] = localfile
    def delete_file(self, localfile):
        del self._files[localfile.hash]

if __name__ == "__main__":
    pass

client.py: client.py:

from user import user
from friend import friend

class client(user):
    _friends = []
    def __init__(self, ip="127.0.0.1", nick="Unnamed"):
        user.__init__(self, ip, nick)
    @property
    def friends(self):
        return self._friends
    @friends.setter
    def friends(self, value):
        self._friends = value
    def add_friend(self, client):
        self._friends.append(client)
    def delete_friend(self, client):
        self._friends.remove(client)

if __name__ == "__main__":
    import shelve

    x = shelve.open("localfile", 'c')

    cliente = client()
    cliente.add_friend(friend("127.0.0.1", "Amigo1"))
    cliente.add_friend(friend("127.0.0.1", "Amigo2"))

    x["client"] = cliente
    print x["client"].friends

    x.close()

Errors: 错误:

facon@facon-E1210:~/Documentos/workspace/test$ python client.py
Traceback (most recent call last):
  File "client.py", line 28, in <module>
    x["client"] = cliente
  File "/usr/lib/python2.7/shelve.py", line 132, in __setitem__
    p.dump(value)
  File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle HASH objects

EDITED 已编辑

Added user.py. 添加了user.py。

Since you can't serialize HASH objects with shelve , you would have to provide the same information in a different way. 由于无法使用shelve序列化HASH对象,因此必须以不同的方式提供相同的信息。 For example, you could only save the digest of the hash. 例如,您只能保存哈希的摘要。

Something in cliente , the instance of client class, is not picklable. cliente中的某些内容( client类的实例)不可腌制。 Here is a list of those types which are picklable . 这是可腌制的那些类型列表

The code you've posted does not show what cliente contains which is not picklable. 你已经发布的代码并不显示什么cliente包含不picklable。 But you can solve the problem by either removing the unpicklable attribute if it is not needed, or by defining __getstate__ and __setstate to make client picklable. 但是您可以通过以下方法解决问题:删除不需要的unpicklable属性,或者定义__getstate____setstate以使client __setstate

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

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