当前位置: 首页 > 科技观察

TinyDB是纯Python编写的轻量级数据库_0

时间:2023-03-12 21:13:53 科技观察

TinyDB是纯Python编写的轻量级数据库,总共只有1800行代码,没有外部依赖。TinyDB的目标是降低小型Python应用程序使用数据库的难度。对于一些简单的程序,最好使用TinyDB而不是SQL数据库,因为它具有以下特点:轻量级:目前源代码有1800行代码(文档占40%左右)和1600行测试代码。可随意迁移:数据库文件生成在当前文件夹下,不带任何服务,可随意迁移。简单:TinyDB通过提供简单干净的API使用户易于使用。用纯Python编写:TinyDB既不需要外部服务器,也不需要任何来自PyPI的依赖项。对于Python3.6+和PyPy3:TinyDB适用于所有现代版本的Python和PyPy。可扩展性强:可以通过编写中间件修改存储行为,轻松扩展TinyDB。100%测试覆盖率:无需解释。1.在开始之前,您需要确保您的计算机上已经成功安装了Python和pip。请选择以下方式之一输入命令安装依赖项:1.Windows环境打开Cmd(开始-运行-CMD)。2.在MacOS环境下,打开Terminal(command+空格进入Terminal)。3.如果你使用的是VSCode编辑器或者Pycharm,可以直接使用界面下方的Terminal.pipinstalltinydb。2、简单的增删改查初始化一个DB文件的例子:fromtinydbimportTinyDBdb=TinyDB('db.json')像这样在当前文件夹下生成一个名为`db.json`的数据库文件。向其中插入数据:fromtinydbimportTinyDBdb=TinyDB('db.json')db.insert({'type':'apple','count':7})db.insert({'type':'peach','count':3})可以看到,我们可以不做任何处理,直接将字典数据插入数据库。下面是批量插入的方法:db.insert_multiple([{'name':'John','age':22},{'name':'John','age':37}])db.insert_multiple({'int':1,'value':i}foriinrange(2))查询所有数据:fromtinydbimportTinyDBdb=TinyDB('db.json')db.all()#[{'count':7,'type':'apple'},{'count':3,'type':'peach'}]除了.all()我们还可以使用for循环遍历db:fromtinydbimportTinyDBdb=TinyDB('db.json')foritemindb:print(item)#{'count':7,'type':'apple'}#{'count':3,'type':'peach'}如果需要搜索特定数据,可以使用Query():fromtinydbimportTinyDBdb=TinyDB('db.json')Fruit=Query()db.search(Fruit.type=='peach')#[{'count':3,'type':'peach'}]db.search(Fruit.count>5)#[{'count':7,'type':'apple'}]更新数据:fromtinydbimportTinyDBdb=TinyDB('db.json')db.update({'foo':'bar'})#DeleteaKeyfromtinydb.operationsimportdeletedb.update(delete('key1'),User.name=='John')删除数据:删除数据也可以使用a条件语句如:fromtinydbimportTinyDBdb=TinyDB('db.json')db.remove(Fruit.count<5)db.all()#[{'count':10,'type':'apple'}]清空整个数据库:fromtinydbimportTinyDBdb=TinyDB('db.json')db.truncate()db.all()#[]3.高级查询除了点运算符访问数据,还可以使用原生的dict访问记法:#Writing1db.search(User.country-code=='foo')#Writing2db.search(User['country-code']=='foo')这两种写法等价于除了常见的查询操作符(==,<,>,...),TinyDB还支持where语句:fromtinydbimportwheredb.search(where('field')=='value')相当于:db.search(Query()['field']=='value')此语法还可以访问嵌套字段:db.search(where('birthday').year==1900)#或db.search(where('birthday')['year']==1900)任意查询方式: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'}]}]检查如果列表中包含单个项目:db.search(User.name.one_of(['jane','john']))TinyDB也支持类似于Pandas的逻辑操作:#Negateaquery:db.search(~(User.name=='John'))#逻辑AND:db.search((User.name=='John')&(User.age<=30))#逻辑OR:db.search((User.name=='John')|(User.name=='Bob'))TinyDB的介绍到此结束,大家也可以访问他们的官方文档查看更多使用方法:https://tinydb.readthedocs.io/en/latest/usage.html特别想基于TinyDB做一些存储优化的同学,可以详细阅读Storage&Mi硬件章节