Home  >  Article  >  Backend Development  >  TinyDB is a lightweight database written purely in Python.

TinyDB is a lightweight database written purely in Python.

WBOY
WBOYforward
2023-05-15 13:19:061272browse

TinyDB 一个纯Python编写的轻量级数据库

TinyDB is a lightweight database written in pure Python, with only 1,800 lines of code in total and no external dependencies.

The goal of TinyDB is to reduce the difficulty of using databases for small Python applications. For some simple programs, instead of using SQL databases, it is better to use TinyDB because it has the following characteristics:

  • Lightweight: The current source code has 1800 lines of code (about 40% of the documentation) and 1600 lines of test code.
  • Can be migrated at will: The database file is generated in the current folder, does not require any service, and can be migrated at will.
  • Simplicity: TinyDB makes it easy for users to use by providing a simple and clean API.
  • Written in pure Python: TinyDB requires neither an external server nor any dependencies from PyPI.
  • Works with Python 3.6 and PyPy3: TinyDB works with all modern versions of Python and PyPy.
  • Powerful scalability: You can easily extend TinyDB by writing middleware to modify the behavior of the storage.
  • 100% Test Coverage: No explanation required.

1. Preparation

Before you start, you must ensure that Python and pip have been successfully installed on your computer.

Please choose any of the following methods to enter the command to install dependencies:

1. Windows environment open Cmd (Start-Run-CMD).

2. MacOS environment Open Terminal (command space and enter Terminal).

3. If you are using VSCode editor or Pycharm, you can directly use the Terminal at the bottom of the interface.

pip install tinydb

2. Simple addition, deletion, modification and query example

Initialize one DB file:

from tinydb import TinyDB
db = TinyDB('db.json')

This generates a database file named `db.json` in the current folder.

Insert data into it:

from tinydb import TinyDB
db = TinyDB('db.json')
db.insert({'type': 'apple', 'count': 7})
db.insert({'type': 'peach', 'count': 3})

As you can see, we can directly insert dictionary data into the database without any processing. The following is the method of batch insertion:

db.insert_multiple([
 {'name': 'John', 'age': 22},
 {'name': 'John', 'age': 37}])
db.insert_multiple({'int': 1, 'value': i} for i in range(2))

Query all data:

from tinydb import TinyDB
db = TinyDB('db.json')
db.all()
# [{'count': 7, 'type': 'apple'}, {'count': 3, 'type': 'peach'}]

In addition to .all(), we can also use a for loop to traverse the db:

from tinydb import TinyDB
db = TinyDB('db.json')
for item in db:
 print(item)
# {'count': 7, 'type': 'apple'}
# {'count': 3, 'type': 'peach'}

If you need to search For specific data, you can use Query():

from tinydb import TinyDB
db = TinyDB('db.json')
Fruit = Query()
db.search(Fruit.type == 'peach')
# [{'count': 3, 'type': 'peach'}]
db.search(Fruit.count > 5)
# [{'count': 7, 'type': 'apple'}]

Update data:

from tinydb import TinyDB
db = TinyDB('db.json')
db.update({'foo': 'bar'})
# 删除某个Key
from tinydb.operations import delete
db.update(delete('key1'), User.name == 'John')

Delete data:

You can also use similar conditional statements to delete data:

from tinydb import TinyDB
db = TinyDB('db.json')
db.remove(Fruit.count < 5)
db.all()
# [{'count': 10, 'type': 'apple'}]

Clear the entire database:

from tinydb import TinyDB
db = TinyDB('db.json')
db.truncate()
db.all()
# []

3. Advanced query

In addition to the dot operator to access data, you can also use the native dict access representation:

# 写法1
db.search(User.country-code == 'foo')
# 写法2
db.search(User['country-code'] == 'foo')

These two The two ways of writing are equivalent.

In addition to the common query operators (==, , ...), TinyDB also supports the where statement:

from tinydb import where
db.search(where('field') == 'value')

This is equivalent to:

db.search(Query()['field'] == 'value')

This syntax can also access nested fields:

db.search(where('birthday').year == 1900)
# 或者
db.search(where('birthday')['year'] == 1900)

Any query method:

db.search(Group.permissions.any(Permission.type == 'read'))
# [{'name': 'user', 'permissions': [{'type': 'read'}]},
# {'name': 'sudo', 'permissions': [{'type': 'read'}, {'type': 'sudo'}]},
# {'name': 'admin', 'permissions':
# [{'type': 'read'}, {'type': 'write'}, {'type': 'sudo'}]}]

Check whether a single item is included in the list:

db.search(User.name.one_of(['jane', 'john']))

TinyDB also supports and Pandas-like logical operations:

# Negate a query:
db.search(~ (User.name == 'John'))
# Logical AND:
db.search((User.name == 'John') & (User.age <= 30))
# Logical OR:
db.search((User.name == 'John') | (User.name == 'Bob'))

The introduction to TinyDB ends here. You can also visit their official documentation to see more usage methods:

​https:/ /www.php.cn/link/8ff3fdef6f5144f50eb2a83cd34baa5d​​​

Especially for students who want to do some storage optimization based on TinyDB, you can read the Storage & Middleware chapter in detail.

The above is the detailed content of TinyDB is a lightweight database written purely in Python.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete