Store dictionary in database

2019-08-09 11:15发布

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 ?

2条回答
Explosion°爆炸
2楼-- · 2019-08-09 11:29

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.

查看更多
做自己的国王
3楼-- · 2019-08-09 11:35

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.

查看更多
登录 后发表回答