-
-
Notifications
You must be signed in to change notification settings - Fork 979
Description
Hi, i'm wondering how to integrate falcon with Tortoise ORM. As far as i know, Tortoise ORM manages transactions on its own, but i'm not sure if it creates a transaction for each request (although i don't see why it would). I already managed to create process_startup and process_shutdown, and i think that to create a new transaction (where exceptions trigger a rollback), you need to use async with in_transaction() wherever you run database queries.
Here you can see an example. There’s one problem: entity_user is fetched in a separate transaction (which can lead to data mismatch), but it should be fetched within a single transaction using in_transaction(). As you can see, it's challenging to manage this without proper middleware. Without in_transaction(), if an exception occurs in verification(), the database will save progress up to that point, which could lead to bugs.
@before(authorize_user, is_logged=True, is_email_verified=False)
class VerifyEmailResource:
async def on_get(self, req: Request, resp: Response):
entity_user: UserType = req.context.entity_user # Got from authorize_user. (Used Tortoise ORM)
async with in_transaction():
await entity_user.verification().start_verification() # Tortoise ORM operations.I'm thinking about creating a decorator to wrap on_get so it would run on_get within a async with in_transaction() block. However, i'm not sure how to do it properly to make it work well with Falcon and Tortoise ORM, also there may be a better solution.
Current middleware:
class TortoiseMiddleware:
async def process_startup(self, scope, event):
await Tortoise.init(config=TORTOISE_ORM)
await Tortoise.generate_schemas()
async def process_shutdown(self, scope, event):
await Tortoise.close_connections()I would really appreciate help with the integration. Also if you have a good solution for other ORM integration, please feel free to share it.