Learning TinyDB on Ubuntu - 03 use TinyDB

143 阅读1分钟

Introduction

This is TinyDB Documentation.
TinyDB is tiny, document oriented and powerfully extensible. Therefore, TinyDB is often used on mobile phone application development. The database Tinydb reads from is of .json type, and is written in the format as below.

{
    "_default": {
        "1": {
            "name": "John",
            "grade": 98
        },
        "2": {
            "name": "Paul",
            "grade": 74
        },
    }
}

Methods

Operating a database is sperated into opening a database, reading a database and writing a database.

Open a Database with TinyDB

To simply open a database from the disk, we can use TinyDB.

from tinydb import TinyDB
db = TinyDB('/path/to/db.json')

To create a new database in memory,

from tinydb.storages import MemoryStorage
db = TinyDB(storage=MemoryStorage)

If you want to cache the database opened from the disk,

from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
db = TinyDB('path/to/db.json', storage=CachingMiddleware(JSONStorage))

What's more, the middleware can be nested

db = TinyDB('path/to/db.json', storage=Middleware1(Middleware2(JSONStorage)))

Read a Database with TinyDB

To simply read a database,

db.all()         # read all documents
iter(db)         # iter over all documents
db.search(query) # get a list of documents matching the query

So we meed to know Class Query and QueryInstance. A QueryInstance example can be generated from Query()

from tinydb.queries import Query
q = Query()
QueryInstance_1 = (q.key1.key2==x)
QueryInstance_2 = (q.key1.key2>a & q.key1.key2<b)
QueryInstance_3 = (q.key1.key2<a | q.key1.key2>b)
QueryInstance_4 = (q.key1.key2.test(f:function->boolean))
QueryInstance_5 = (q.key1.key2.matches('[aZ]*'))

or where()

from tinydb.queries import where
QueryInstance_6 = where(q.key1.key2.operations())

Write a Database with TinyDB

To simply write a database,

db.insert(JSON/document)          # insert a document
db.update(fields, query/document) # update a document or documents fit query
db.upsert(document)               # update or insert a document
db.remove(query)                  # remove documents fit query
db.truncate()                     # remove all documents

To generate a document, we can use

from tinydb.table import Document
DocumentExample = Document(JSON, doc_id=num)