Sobes.tech
Middle+

import psycopg2 def save_prediction(text: str, result: str): conn = psycopg2.connect("host=db user=app password=secret dbname=ml") cur = conn.cursor() cur.execute( "INSERT INTO predictions (input, output) VALUES (%s, %s)", (text, result) ) conn.commit() cur.close()

sobes.tech AI

Answer from AI

The provided code has several issues related to resource management and error handling:

  1. The connection to the database and the cursor are not closed in case of an exception, which can lead to resource leaks.
  2. It is better to use context managers with for automatic closing of the connection and cursor.

Here's a corrected version of the function:

import psycopg2

def save_prediction(text: str, result: str):
    try:
        with psycopg2.connect("host=db user=app password=secret dbname=ml") as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "INSERT INTO predictions (input, output) VALUES (%s, %s)",
                    (text, result)
                )
            # commit is called automatically upon exiting the with block
    except psycopg2.Error as e:
        print(f"Error saving prediction: {e}")
        # Logging or re-raising the exception can be added here

This approach guarantees proper closing of the connection and cursor, as well as error handling.