纯Python开发面向文档的数据库:TinyDB
jopen
10年前
TinyDB是为了你的幸福而优化的微小的,面向文档的数据库。它采用纯Python开发并且没有额外的需求。它非常适合于小的应用。
TinyDB 特性:
- tiny: 当前源代码只有1200行(+ 600 lines tests). For comparison: Buzhug has about 2000 lines of code (w/o tests), CodernityDB has about 8000 lines of code (w/o tests).
- document oriented: 类似 MongoDB, 你可以在TinyDB中存储任何文档(represented as dict)
- optimized for your happiness: TinyDB的设计是简单而有趣提供了一个简单和干净的API来使用。
- written in pure Python: TinyDB neither needs an external server (as e.g. PyMongo) nor any dependencies from PyPI.
- works on Python 2.6 – 3.4 and PyPy: TinyDB works on all modern versions of Python and PyPy.
- easily extensible: You can easily extend TinyDB by writing new storages or modify the behaviour of storages with Middlewares.
- nearly 100% test coverage: If you don't count that __repr__ methods and some abstract methods are not tested, TinyDB has a test coverage of 100%.
Example Code
>>> from tinydb import TinyDB, where >>> db = TinyDB('/path/to/db.json') >>> db.insert({'int': 1, 'char': 'a'}) >>> db.insert({'int': 1, 'char': 'b'})
Query Language
>>> # Search for a field value >>> db.search(where('int') == 1) [{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}] >>> # Combine two queries with logical and >>> db.search((where('int') == 1) & (where('char') == 'b')) [{'int': 1, 'char': 'b'}] >>> # Combine two queries with logical or >>> db.search((where('char') == 'a') | (where('char') == 'b')) [{'int': 1, 'char': 'a'}, {'int': 1, 'char': 'b'}] >>> # More possible comparisons: != < > <= >= >>> # More possible checks: where(...).matches(regex), where(...).test(your_test_func)
Tables
>>> table = db.table('name') >>> table.insert({'value': True}) >>> table.all() [{'value': True}]
Using Middlewares
>>> from tinydb.storages import JSONStorage >>> from tinydb.middlewares import CachingMiddleware >>> db = TinyDB('/path/to/db.json', storage=CachingMiddleware(JSONStorage))