-
Notifications
You must be signed in to change notification settings - Fork 0
/
background_task.py
38 lines (31 loc) · 1.25 KB
/
background_task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import asyncio
from models.settings.postgres.connection import PostgresConnectionHandler
from models.repository.user_postgres_repository import UserPostgresRepository
async def backend_task(child_conn):
"""
Perform a background task to insert user data into a PostgreSQL database.
Args:
child_conn: A multiprocessing connection object for communication with the parent process.
Returns:
None
Raises:
Exception: If an error occurs during the database connection or user insertion.
"""
while True:
message = await asyncio.get_event_loop().run_in_executor(None, child_conn.recv)
if message == []:
break
try:
connection = PostgresConnectionHandler()
await connection.connect_to_db()
for user in message:
await UserPostgresRepository(
connection.get_connection()
).insert_user(
username=user["username"],
email=user["email"],
age=user["age"]
)
await connection.close_connection()
except Exception as e:
print(f"Aqui está sendo gerado um erro: {e}")