Implementing async transactions with asyncio
The asyncio
module is an easy-to-use library for implementing asynchronous tasks. Compared to the threading
module, the asyncio
utilities use an event loop to execute each task, which is lightweight and easier to control. Threading uses one whole thread to run one specific operation, while asyncio
utilizes only a single event loop to run all registered tasks concurrently. Thus, constructing an event loop is more resource friendly than running multiple threads to build concurrent transactions.
asyncio
is seamlessly compatible with flask[async]
, and the clear proof is the following API function that adds a new voter to the DB using the task created by the create_task()
method:
from app.model.db import Member from app.repository.member import MemberRepository from app.model.config import db_session from asyncio import create_task, ensure_future, InvalidStateError from app.exceptions.db import DuplicateRecordException @current_app.post...