API Documentation

tinydb.database

Contains the database and tables implementation.

class tinydb.database.Table(name, db)

Represents a single TinyDB Table.

__contains__(condition)

Equals to bool(table.search(condition))).

__enter__()

Allow the database to be used as a context manager.

Returns:the table instance
__exit__(*args)

Try to close the storage after being used as a context manager.

__init__(name, db)

Get access to a table.

Parameters:
__len__()

Get the total number of elements in the table.

all()

Get all elements stored in the table.

Note: all elements will have an _id key.

Returns:a list with all elements.
Return type:list[dict]
contains(cond)

Check wether the database contains an element matching a condition.

Parameters:cond (Query) – the condition use
count(cond)

Count the elements matching a condition.

Parameters:cond (Query) – the condition use
get(cond)

Search for exactly one element matching a condition.

Note: all elements will have an _id key.

Parameters:cond (Query) – the condition to check against
Returns:the element or None
Return type:dict or None
insert(element)

Insert a new element into the table.

element has to be a dict, not containing the key ‘id’.

purge()

Purge the table by removing all elements.

remove(cond)

Remove the element matching the condition.

Parameters:cond (query, int, list) – the condition to check against
search(cond)

Search for all elements matching a ‘where’ cond.

Note: all elements will have an _id key.

Parameters:cond (Query) – the condition to check against
Returns:list of matching elements
Return type:list
update(fields, cond)

Update all elements matching the condition to have a given set of fields.

Parameters:
  • fields (dict) – the fields that the matching elements will have
  • cond (query) – which elements to update
class tinydb.database.TinyDB(*args, **kwargs)

The main class of TinyDB.

Gives access to the database, provides methods to insert/search/remove and getting tables.

__contains__(item)

A shorthand for query(...) == ... in db.table(). Intendet to be used in if-clauses (avoiding if len(db.serach(...)):)

>>> if where('field') == 'value' in db:
...     print True
__enter__()

See Table.__enter__()

__exit__(*args)

See Table.__exit__()

__getattr__(name)

Forward all unknown attribute calls to the underlying standard table.

__init__(*args, **kwargs)

Create a new instance of TinyDB.

All arguments and keyword arguments will be passed to the underlying storage class (default: JSONStorage).

__len__()

Get the total number of elements in the DB.

>>> len(db)
0
purge_tables()

Purge all tables from the database. CANT BE REVERSED!

table(name='_default')

Get access to a specific table.

Creates a new table, if it hasn’t been created before, otherwise it returns the cached Table object.

Parameters:name (str) – The name of the table.

tinydb.queries

Contains the querying interface.

Starting with Query you can construct complex queries:

>>> ((where('f1') == 5) & (where('f2') != 2)) | where('s').matches('^\w+$')
(('f1' == 5) and ('f2' != 2)) or ('s' ~= ^\w+$ )

Queries are executed by using the __call__:

>>> q = where('val') == 5
>>> q({'val': 5})
True
>>> q({'val': 1})
False
class tinydb.queries.Query(key)

Provides methods to do tests on dict fields.

Any type of comparison will be called in this class. In addition, it is aliased to where to provide a more intuitive syntax.

When not using any comparison operation, this simply tests for existence of the given key.

__call__(element)

Run the test on the element.

Parameters:element (dict) – The dict that we will run our tests against.
__eq__(other)

Test a dict value for equality.

>>> where('f1') == 42
'f1' == 42
__ge__(other)

Test a dict value for being greater than or equal to another value.

>>> where('f1') >= 42
'f1' >= 42
__gt__(other)

Test a dict value for being greater than another value.

>>> where('f1') > 42
'f1' > 42
__invert__()

Negates a query.

>>> ~(where('f1') >= 42)
not ('f1' >= 42)
Return type:tinydb.queries.QueryNot
__le__(other)

Test a dict value for being lower than or equal to another value.

>>> where('f1') <= 42
'f1' <= 42
__lt__(other)

Test a dict value for being lower than another value.

>>> where('f1') < 42
'f1' < 42
__ne__(other)

Test a dict value for inequality.

>>> where('f1') != 42
'f1' != 42
matches(regex)

Run a regex test against a dict value.

>>> where('f1').matches('^\w+$')
'f1' ~= ^\w+$
Parameters:regex – The regular expression to pass to re.match
Return type:QueryRegex
test(func)

Run a user-defined test function against a dict value.

>>> def test_func(val):
...     return val == 42
...
>>> where('f1').test(test_func)
'f1'.test(<function test_func at 0x029950F0>)
Parameters:func – The function to run. Has to accept one parameter and return a boolean.
Return type:QueryCustom
class tinydb.queries.AndOrMixin

A mixin providing methods calls & and |.

All queries can be combined with & and |. Thus, we provide a mixin here to prevent repeating this code all the time.

__and__(other)

Combines this query and another with logical and.

Example:

>>> (where('f1') == 5) & (where('f2') != 2)
('f1' == 5) and ('f2' != 2)
Return type:QueryAnd
__or__(other)

Combines this query and another with logical or.

Example:

>>> (where('f1') == 5) | (where('f2') != 2)
('f1' == 5) or ('f2' != 2)
Return type:QueryOr

tinydb.storage

Contains the base class for storages and two implementations.

class tinydb.storages.JSONStorage(path)

Store the data in a JSON file.

__init__(path)

Create a new instance.

Also creates the storage file, if it doesn’t exist.

Parameters:path (str) – Where to store the JSON data.
class tinydb.storages.MemoryStorage

Store the data as JSON in memory.

__init__()

Create a new instance.

tinydb.middlewares

Contains the base class for middlewares and two implementations.

class tinydb.middlewares.CachingMiddleware(storage_cls)

Add some caching to TinyDB.

This Middleware aims to improve the performance of TinyDB by writing only the last DB state every WRITE_CACHE_SIZE time and reading always from cache.

flush()

Flush all unwritten data to disk.

class tinydb.middlewares.ConcurrencyMiddleware(storage_cls)

Makes TinyDB working with multithreading.

Uses a lock so write/read operations are virtually atomic.

About TinyDB

TinyDB is a tiny, document oriented database optimized for your happiness :)

Useful Links

Table Of Contents

Navigation