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

2 投票
2 回答
3700 浏览
提问于 2025-04-17 10:50

我该如何把哈希对象转换成可以存储的格式呢?我正在使用 shelve 来存储很多对象。

层级结构:

- user
    - client
    - friend

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 文件:

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()

错误信息:

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

已编辑

添加了 user.py 文件。

2 个回答

0

cliente这个对象里,属于client类的实例,有些东西是不能被“打包”的。你可以查看这个列表,看看哪些类型是可以被打包的

你发的代码没有显示cliente里面有什么东西是不能被打包的。不过,你可以通过两种方式来解决这个问题:要么把那些不需要的、不能打包的属性去掉,要么定义__getstate____setstate__,这样就能让client变得可以被打包了。

5

因为你不能用 shelve 来保存 HASH 对象,所以你需要用其他方式来提供相同的信息。比如,你可以只保存这个哈希值的摘要。

撰写回答