retry a query after a OperationalError or InternalError #993
dfroger-idnow
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
The problem
I want to implement a "retry" mechanism for a web service (FastAPI) I'm working on.
Basically, a MariaDB Connection and a Cursor are provided (via Dependency Injection) to the Python coroutine function that handles an HTTP request and, is case of OperationalError (maybe a network issues closes the underlying connection) or InternalError , I want to acquire a new Connection/Cursor to retry the query.
The
aiomysql
library provides context manager for both Connection and Cursor. Putting all the coroutine function that handles an HTTP request in their context was my first idea, but it's not suitable to re-acquiring the Connection/Cursor for retry:Instead, I propose to put the coroutine function for the HTTP request inside the context of a
DatabaseRetryContext
context manager, which exposes a Connection/Cursor, and a method to re-acquire them. The pseudo-code now becomes:The solution implementation
Here is the proposed implementation of the
DatabaseRetryContext
:How to use it
Functions that perform database queries can takes a
DatabaseRetryContext
as first argument, and be decorated by aretry
function. For example:If a function do not use connection pool or retry, a simple
DatabaseContext
can be used instead.And a
retry
function could be for example:Questions
What do you thing about the problem I'm trying to solve: retry with a new Connection/Cursor when OperationalError/InternalError occurs?
What do you thing about the proposed solution, is there are better/simpler approach?
What do you thing about a Pull Request to include
DatabaseRetryContext
inaiomysql
: is the problem it solves common enough, and the solution generic enough? I would expect theretry
function (maybe simplified version) to be in the documentation as possible example of how to useDatabaseRetryContext
.Thanks for readying!
Beta Was this translation helpful? Give feedback.
All reactions