2012-01-22 10 views
1

ハッシュオブジェクトをシリアル化するにはどうすればいいですか?シェルブには多くのオブジェクトを格納するために使用しています。Pythonでハッシュオブジェクトをシリアライズする方法

階層:

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

エラー:

[email protected]:~/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

user.pyを追加しました。

+0

すべてのモジュールが 'if __name__ == '__main __''ブロックを必要とするわけではありませんが、それはuser.pyで役に立ちません。 – Gandaro

+0

あなたは正しいです、ユーザーは抽象クラスであると考えられます。 – Facon

答えて

4

shelveHASHオブジェクトをシリアル化することはできないため、同じ情報を別の方法で入力する必要があります。たとえば、ハッシュのダイジェストのみを保存することができます。

+0

私は両方のもの、キー(文字列)と要素(ピクルできるオブジェクト)が必要です。私は両方の要素を2つのリストに入れたいと考えています.1つはキー用、もう1つは要素用です。しかし、後で私がリストに正しく参加できるかどうかはわかりません。 – Facon

+0

次に、2つの要素を持つタプルの辞書またはリストを使用します。 – Gandaro

+0

Omg !,私はばかだ、私はあなたが言ったようにこれを変更する必要があります:self._id = hashlib.sha1(str(time.time()))to self._id = hashlib.sha1(str(time。 time()))。hexdigest()を実行すると、オブジェクトをピクルすることができます。私はハッシュがすでにストリングだと思った。ありがとう!!!! – Facon

0

clienteのインスタンス、clientクラスのインスタンスは、picklableではありません。 こちらはlist of those types which are picklableです。

投稿したコードには、決済可能ではないclienteの内容が表示されません。しかし、不要な属性を削除するか、__getstate____setstateと定義してclientをpicklableにすることで、問題を解決できます。

+0

私はクライアントから継承するクラスを投稿しました。このクラスには、おそらく "ハッシュ要素"、ユーザー、今すぐ確認してください。私は自分のコードを改善するための批判も受け入れます。 – Facon

関連する問題