forked from tortoise/tortoise-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.py
More file actions
52 lines (40 loc) · 1.19 KB
/
router.py
File metadata and controls
52 lines (40 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
This example to use router to implement read/write separation
"""
from typing import Type
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model
class Event(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
datetime = fields.DatetimeField(null=True)
class Meta:
table = "event"
def __str__(self):
return self.name
class Router:
def db_for_read(self, model: Type[Model]):
return "slave"
def db_for_write(self, model: Type[Model]):
return "master"
async def run():
config = {
"connections": {"master": "sqlite:///tmp/test.db", "slave": "sqlite:///tmp/test.db"},
"apps": {
"models": {
"models": ["__main__"],
"default_connection": "master",
}
},
"routers": ["__main__.Router"],
"use_tz": False,
"timezone": "UTC",
}
await Tortoise.init(config=config)
await Tortoise.generate_schemas()
# this will use connection master
event = await Event.create(name="Test")
# this will use connection slave
await Event.get(pk=event.pk)
if __name__ == "__main__":
run_async(run())