Store dictionary in database

痴心易碎 提交于 2019-12-24 18:06:10

问题


I create a Berkeley database, and operate with it using bsddb module. And I need to store there information in a style, like this:

username = '....'
notes = {'name_of_note1':{
                          'password':'...',
                          'comments':'...',
                          'title':'...'
                         }
         'name_of_note2':{
                           #keys same as previous, but another values
                         }
        }

This is how I open database

db = bsddb.btopen['data.db','c']

How do I do that ?


回答1:


So, first, I guess you should open your database using parentheses:

db = bsddb.btopen('data.db','c')

Keep in mind that Berkeley's pattern is key -> value, where both key and value are string objects (not unicode). The best way in your case would be to use:

db[str(username)] = json.dumps(notes)

since your notes are compatible with the json syntax.

However, this is not a very good choice, say, if you want to query only usernames' comments. You should use a relational database, such as sqlite, which is also built-in in Python.




回答2:


A simple solution was described by @Falvian.

For a start there is a column pattern in ordered key/value store. So the key/value pattern is not the only one.

I think that bsddb is viable solution when you don't want to rely on sqlite. The first approach is to create a documents = bsddb.btopen['documents.db','c'] and store inside json values. Regarding the keys you have several options:

  • Name the keys yourself, like you do "name_of_note_1", "name_of_note_2"
  • Generate random identifiers using uuid.uuid4 (don't forget to check it's not already used ;)
  • Or use a row inside this documents with key=0 to store a counter that you will use to create uids (unique identifiers).

If you use integers don't forget to pack them with lambda x: struct.pack('>q', uid) before storing them.

If you need to create index. I recommend you to have a look at my other answer introducting composite keys to build index in bsddb.



来源:https://stackoverflow.com/questions/21934806/store-dictionary-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!