python的简单异步orm,考虑到关系而构建
tortoise-orm的Python项目详细描述
简介
tortoise orm是一个易于使用的asyncioorm(对象关系映射器)灵感来自django。
乌龟虫是建立在关系和钦佩优秀和流行的django虫。 它的设计中铭刻着这样一个概念:你不仅要处理表,还要处理关系数据。
您可以在ReadTheDocs
注意
乌龟虫是一个年轻的项目,突破性的变化是意料之中的。 我们保留一张Changelog的,它可能有破损的清晰记录。
对于sqlite、mysql和postgresql,cpython>;=3.5.3支持tortoise orm;对于sqlite和mysql,pypy3.6>;=7.1支持tortoise orm。
为什么要造乌龟?
Python有许多现有的和成熟的ORMS,不幸的是,它们被设计成一个相反的I/O如何处理的范例。 asyncio是一种相对较新的技术,具有非常不同的并发模型,最大的变化是关于如何处理I/O。
然而,tortoise orm并不是第一次尝试构建asyncioorm,有很多开发人员试图将同步python orms映射到异步世界,最初的尝试没有干净的api。
于是我们开始了龟形。
Tortoise orm的设计是功能性的,但是很熟悉,它可以帮助希望切换到asyncio的开发人员轻松地迁移。
与其他python orms相比,它的性能也很好,只输给了pony orm:
orm有何用处?
当您构建一个使用关系数据库的应用程序或服务时,有一点是您不能仅仅使用参数化查询甚至查询生成器,您只需不断重复自己,为每个实体编写稍微不同的代码。 代码不知道数据之间的关系,因此您最终几乎是手动连接数据。 在访问数据库的方式上也很容易出错,使sql注入攻击很容易发生。 您的数据规则也被分发,增加了管理数据的复杂性,甚至更糟的是,应用不一致。
设计了一个orm(object relational mapper)来解决这些问题,方法是集中化数据模型和数据规则,确保安全地管理数据(提供对sql注入的免疫力),并跟踪关系,这样就不必这样做了。
开始
安装
首先,您必须像这样安装tortoise:
pip install tortoise-orm
然后您应该安装数据库驱动程序
pip install asyncpg aiosqlite
快速教程
乌龟的主要实体是tortoise.models.Model。 您可以开始编写这样的模型:
fromtortoise.modelsimportModelfromtortoiseimportfieldsclassTournament(Model):id=fields.IntField(pk=True)name=fields.TextField()def__str__(self):returnself.nameclassEvent(Model):id=fields.IntField(pk=True)name=fields.TextField()tournament=fields.ForeignKeyField('models.Tournament',related_name='events')participants=fields.ManyToManyField('models.Team',related_name='events',through='event_team')def__str__(self):returnself.nameclassTeam(Model):id=fields.IntField(pk=True)name=fields.TextField()def__str__(self):returnself.name
在您定义了所有模型之后,tortoise需要您初始化它们,以便在模型之间创建向后关系,并用适当的模型匹配您的db客户机。
你可以这样做:
fromtortoiseimportTortoiseasyncdefinit():# Here we connect to a SQLite DB file.# also specify the app name of "models"# which contain models from "app.models"awaitTortoise.init(db_url='sqlite://db.sqlite3',modules={'models':['app.models']})# Generate the schemaawaitTortoise.generate_schemas()
在这里,我们在名为db.sqlite3的本地目录中创建到sqlite数据库的连接,然后发现初始化模型。
龟形虫目前支持以下数据库:
- sqlite
- PostgreSQL(需要^{TT7}$)
- mysql(需要aiomysql)
generate_schema在空数据库上生成架构。默认情况下,tortoise以安全模式生成模式 如果不存在则包含子句,因此您可以在主代码中包含它。
之后,您可以开始使用您的模型:
# Create instance by savetournament=Tournament(name='New Tournament')awaittournament.save()# Or by .create()awaitEvent.create(name='Without participants',tournament=tournament)event=awaitEvent.create(name='Test',tournament=tournament)participants=[]foriinrange(2):team=Team.create(name='Team {}'.format(i+1))participants.append(team)# M2M Relationship management is quite straightforward# (also look for methods .remove(...) and .clear())awaitevent.participants.add(*participants)# You can query related entity just with async forasyncforteaminevent.participants:pass# After making related query you can iterate with regular for,# which can be extremely convenient for using with other packages,# for example some kind of serializers with nested supportforteaminevent.participants:pass# Or you can make preemptive call to fetch related objectsselected_events=awaitEvent.filter(participants=participants[0].id).prefetch_related('participants','tournament')# Tortoise supports variable depth of prefetching related entities# This will fetch all events for team and in those events tournaments will be prefetchedawaitTeam.all().prefetch_related('events__tournament')# You can filter and order by related models tooawaitTournament.filter(events__name__in=['Test','Prod']).order_by('-events__participants__name').distinct()
贡献
许可证
此项目在apache许可下获得许可-有关详细信息,请参见LICENSE.txt文件