sqlitemapSQLite數據庫的字典接口。
…有一天,我需要一個嵌入式鑰匙值商店來進行寵物項目,但沒有找到“足夠好”的實現。所以,我做了自己的。
這是標準SQLite3模塊上的輕巧包裝器。它為SQLite連接和SQLite表提供了標準的MutableMapping接口。
Connection您可以創建一個Connection的實例,就好像是普通的sqlite3.connect調用:
from sqlitemap import Connection
connection = Connection ( ':memory:' , ...)它實現了上下文管理器接口,因此您可以with交易,就好像它是sqlite3.Connection一樣。除了__setitem__外,它實現了MutableMapping[str, Collection] 。因此,您可以想像Connection作為藏品的詞典與他們的名字完全兼而有之,並且幾乎可以用正常的dict做所有您可以做的一切:
from sqlitemap import Collection
# Collection is automatically created:
foo : Collection = connection [ 'foo' ]
# You can iterate over collection names:
names = list ( connection )
# Or even over collections:
collections = connection . values ()
# Drop collection:
del connection [ 'foo' ]
# Get number of collections:
len ( connection )
# Special one, to close the connection:
connection . close ()在內部,收集是一個具有兩列的表: key: str和value: bytes 。因此,您需要一些序列化將對象表示為字節字符串。默認情況下, sqlitemap使用標準json模塊。如果有的話,它可以撿起ujson或orjson 。這些也可作為sqlitemap Extras提供: sqlitemap[ujson]和sqlitemap[orjson] 。
否則,您可以為編碼器指定任何自定義Callable[[Any], bytes] ,並為解碼器Callable[[bytes], Any] :
connection = Connection ( ':memory:' , dumps_ = custom_dumps , loads_ = custom_loads )Collection Collection還實現了上下文管理器接口以進行交易,並MutableMapping[str, Any] :
with raises ( KeyError ):
_ = collection [ 'foo' ]
collection [ 'foo' ] = 'bar'
assert collection [ 'foo' ] == 'bar'
collection [ 'foo' ] = 'qux'
assert collection [ 'foo' ] == 'qux' key列是主要鍵。
assert list ( collection ) == []
collection [ 'foo' ] = 'bar'
assert list ( collection ) == [ 'foo' ] assert collection . values () == []
collection [ 'foo' ] = 'bar'
assert collection . values () == [ 'bar' ] with raises ( KeyError ):
del collection [ 'foo' ]
collection [ 'foo' ] = 42
del collection [ 'foo' ]
with raises ( KeyError ):
del collection [ 'foo' ]Collection.__getitem__和Collection.__setitem__也支持切片作為論點。然後將切片start轉換為key >= start子句, stop到key < stop和step到key LIKE step 。所有這些都與AND員結合使用。 Collection.__getitem__也ORDER BY key ,因此可以進行一些更複雜的查詢:
collection [ 'bar' ] = 1
collection [ 'foo' ] = 2
collection [ 'quw' ] = 3
collection [ 'qux' ] = 4
collection [ 'quy' ] = 5
collection [ 'quz' ] = 6
assert collection [ 'foo' :] == [ 2 , 3 , 4 , 5 , 6 ]
assert collection [: 'foo' ] == [ 1 ]
assert collection [:: 'qu%' ] == [ 3 , 4 , 5 , 6 ]
assert collection [ 'bar' : 'quz' : 'qu%' ] == [ 3 , 4 , 5 ]這也與del collection [...]一起使用。它刪除將使用相應的__getitem__調用將選擇的行:
collection [ 'bar' ] = 1
collection [ 'foo' ] = 2
collection [ 'quw' ] = 3
collection [ 'qux' ] = 4
collection [ 'quy' ] = 5
collection [ 'quz' ] = 6
del collection [ 'bar' : 'quz' : 'qu%' ]
assert list ( collection ) == [ 'bar' , 'foo' , 'quz' ]sqlitemap對控制交易沒有什麼特別的作用。為此,請參閱標準庫文檔。