Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply transaction logic in FastAPI RealWorld example app?

I am using nsidnev/fastapi-realworld-example-app.

I need to apply transaction logic to this project.

In one API, I am calling a lot of methods from repositories and doing updating, inserting and deleting operations in many tables. If there is an exception in any of these operations, how can I roll back changes? (Or if everything is correct then commit.)

like image 951
sevdimali Avatar asked Nov 17 '21 10:11

sevdimali


People also ask

When does fastapi call a function?

This is a Python function. It will be called by FastAPI whenever it receives a request to the URL " / " using a GET operation. In this case, it is an async function.

What are the alternatives to fastapi?

And there are dozens of alternatives, all based on OpenAPI. You could easily add any of those alternatives to your application built with FastAPI. You could also use it to generate code automatically, for clients that communicate with your API. For example, frontend, mobile or IoT applications.

How do I use fastapi in recrecap?

Recap, step by step. 1 Step 1: import FastAPI. from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} FastAPI is a ... 2 Step 2: create a FastAPI "instance". 3 Step 3: create a path operation. 4 Step 4: define the path operation function. 5 Step 5: return the content.

What is the difference between OpenAPI and fastapi operations?

So, in OpenAPI, each of the HTTP methods is called an "operation". We are going to call them " operations " too. The @app.get ("/") tells FastAPI that the function right below is in charge of handling requests that go to: That @something syntax in Python is called a "decorator".


1 Answers

nsidnev/fastapi-realworld-example-app is using asyncpg.

There are two ways to use Transactions.

1. async with statement

async with conn.transaction():
    await repo_one.update_one(...)
    await repo_two.insert_two(...)
    await repo_three.delete_three(...)

    # This automatically rolls back the transaction:
    raise Exception

2. start, rollback, commit statements

tx = conn.transaction()
await tx.start()

try:
    await repo_one.update_one(...)
    await repo_two.insert_two(...)
    await repo_three.delete_three(...)
except:
    await tx.rollback()
    raise
else:
    await tx.commit()

Getting the connection conn in routes

Inject conn: Connection = Depends(_get_connection_from_pool).

from asyncpg.connection import Connection
from fastapi import Depends

from app.api.dependencies.database import _get_connection_from_pool


@router.post(
    ...
)
async def create_new_article(
    ...
    conn: Connection = Depends(_get_connection_from_pool),  # Add this
) -> ArticleInResponse:
like image 62
aaron Avatar answered Oct 19 '22 06:10

aaron