question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Preferred way to commit/rollback

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

When read about FastAPI’s dependency system with yield state, its pretty tempting to use database transactions with them like so:

async def get_db(request: Request):
    """ database: Database = Depends(get_db) """
    database: Database = request.app.state.database
    async with database.transaction():
        yield database

But this is incorrect way to do it because if transaction would not commit (teardown code in async with raises error) then there is no way to change response.

So this case about transactions would be good to note in docs for dependencies with yield statement (that this is incorrect way). Maybe add link to starlette docs about transactions: https://www.starlette.io/database/#transactions.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
lephuongbgcommented, Oct 15, 2020

You could use middleware to have every endpoint automatically wrapped in transaction like us:

async def automatic_transaction(request: Request, call_next):
    """Wrap all data-modifying requests in transaction"""
    from models import db # We use peewee

    if request.method.lower() in ("post", "put", "patch", "delete"):
        with db.atomic() as txn: # Auto-rollback transaction on server exception
            response = await call_next(request)
            if txn.status_code >= 400: # Auto-rollback transaction on handled exception
                txn.rollback()
    else:
        response = await call_next(request)

    return response

app.add_middleware(BaseHTTPMiddleware, dispatch=automatic_transaction)
1reaction
artslobcommented, Oct 9, 2020

Good. I vote for 2 things:

  1. Add a warning to dependency injection docs that its bad place to make a transaction
  2. Maybe add link to Starlette docs about transactions
Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL Commit And Rollback - DigitalOcean
COMMIT and ROLLBACK are two such keywords which are used in order store and revert the process of data storage. These keywords are...
Read more >
How to rollback using explicit SQL Server transactions
In this article, we will learn how to rollback using explicit SQL Server transactions.
Read more >
Difference between COMMIT and ROLLBACK in SQL
COMMIT in SQL is a transaction control language that is used to permanently save the changes done in the transaction in tables/databases.
Read more >
Should I commit or rollback a read transaction? - Stack Overflow
The transaction will be committed or rolled back one way or another, so best practice would be to always issue a commit if...
Read more >
ROLLBACK TRANSACTION (Transact-SQL) - SQL Server
A transaction cannot be rolled back after a COMMIT TRANSACTION statement is executed, except when the COMMIT TRANSACTION is associated with a ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found