LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
Wrapping database operations in a context manager (#1253)
Rahul Johnya48d20ae8ad9
diff --git a/prompt-service/src/unstract/prompt_service/config.py b/prompt-service/src/unstract/prompt_service/config.pyindex f5e993c06..725d1f282 100644--- a/prompt-service/src/unstract/prompt_service/config.py+++ b/prompt-service/src/unstract/prompt_service/config.py@@ -4,10 +4,7 @@ from os import environ as envfrom dotenv import load_dotenvfrom flask import Flaskfrom unstract.prompt_service.controllers import api-from unstract.prompt_service.extensions import db-from unstract.prompt_service.helpers.lifecycle import register_lifecycle_hooksfrom unstract.prompt_service.helpers.plugin import plugin_loader-from unstract.prompt_service.utils.env_loader import get_env_or_diefrom unstract.sdk.constants import LogLevelfrom unstract.core.flask import register_error_handlers, register_request_id_middleware@@ -25,27 +22,9 @@ def create_app() -> Flask:app = Flask("prompt-service")app.logger.setLevel(log_level)app.logger.info("Initializing Flask application...")- # Load required environment variables- db_host = get_env_or_die("PG_BE_HOST")- db_port = get_env_or_die("PG_BE_PORT")- db_user = get_env_or_die("PG_BE_USERNAME")- db_pass = get_env_or_die("PG_BE_PASSWORD")- db_name = get_env_or_die("PG_BE_DATABASE")- application_name = env.get("APPLICATION_NAME", "unstract-prompt-service")-- # Initialize and connect to the database- db.init(- database=db_name,- user=db_user,- password=db_pass,- host=db_host,- port=db_port,- options=f"-c application_name={application_name}",- )# Load pluginsplugin_loader(app)- register_lifecycle_hooks(app)register_request_id_middleware(app)register_error_handlers(app)app.register_blueprint(api)diff --git a/prompt-service/src/unstract/prompt_service/extensions.py b/prompt-service/src/unstract/prompt_service/extensions.pyindex ffa750da0..8fc934a55 100644--- a/prompt-service/src/unstract/prompt_service/extensions.py+++ b/prompt-service/src/unstract/prompt_service/extensions.py@@ -1,3 +1,35 @@-from peewee import PostgresqlDatabase+from collections.abc import Generator+from contextlib import contextmanager+from os import environ as env+from typing import Any-db = PostgresqlDatabase(None)+from playhouse.postgres_ext import PostgresqlExtDatabase+from unstract.prompt_service.utils.env_loader import get_env_or_die++# Load required environment variables+db_host = get_env_or_die("PG_BE_HOST")+db_port = get_env_or_die("PG_BE_PORT")+db_user = get_env_or_die("PG_BE_USERNAME")+db_pass = get_env_or_die("PG_BE_PASSWORD")+db_name = get_env_or_die("PG_BE_DATABASE")+application_name = env.get("APPLICATION_NAME", "unstract-prompt-service")++# Initialize and connect to the database+db = PostgresqlExtDatabase(+ database=db_name,+ user=db_user,+ host=db_host,+ password=db_pass,+ port=db_port,+ options=f"-c application_name={application_name}",+)+++@contextmanager+def db_context() -> Generator[PostgresqlExtDatabase, Any, None]:+ try:+ db.connect()+ yield db+ finally:+ if not db.is_closed():+ db.close()diff --git a/prompt-service/src/unstract/prompt_service/helpers/auth.py b/prompt-service/src/unstract/prompt_service/helpers/auth.pyindex 457a8f3f8..362a123ed 100644--- a/prompt-service/src/unstract/prompt_service/helpers/auth.py+++ b/prompt-service/src/unstract/prompt_service/helpers/auth.py@@ -4,7 +4,7 @@ from flask import Requestfrom flask import current_app as appfrom flask import requestfrom unstract.prompt_service.constants import DBTableV2-from unstract.prompt_service.extensions import db+from unstract.prompt_service.extensions import db, db_contextfrom unstract.prompt_service.utils.db_utils import DBUtilsfrom unstract.prompt_service.utils.env_loader import get_env_or_die@@ -21,11 +21,11 @@ class AuthHelper:return Falseplatform_key_table = f'"{DB_SCHEMA}".{DBTableV2.PLATFORM_KEY}'-- query = f"SELECT * FROM {platform_key_table} WHERE key = '{token}'"- cursor = db.execute_sql(query)- result_row = cursor.fetchone()- cursor.close()+ with db_context():+ query = f"SELECT * FROM {platform_key_table} WHERE key = '{token}'"+ cursor = db.execute_sql(query)+ result_row = cursor.fetchone()+ cursor.close()if not result_row or len(result_row) == 0:app.logger.error(f"Authentication failed. bearer token not found {token}"diff --git a/prompt-service/src/unstract/prompt_service/helpers/lifecycle.py b/prompt-service/src/unstract/prompt_service/helpers/lifecycle.pydeleted file mode 100644index c1d2121d1..000000000--- a/prompt-service/src/unstract/prompt_service/helpers/lifecycle.py+++ /dev/null@@ -1,25 +0,0 @@-from typing import Any--from flask import Flask, request-from unstract.prompt_service.extensions import db---def register_lifecycle_hooks(app: Flask):- @app.before_request- def before_request() -> None:- """Ensure the DB connection is open before handling the request."""- if db.is_closed():- db.connect(reuse_if_open=True)- app.logger.info(f"Request Path: {request.path} | Method: {request.method}")-- @app.teardown_request- def teardown_request(exception: Any) -> None:- """Close the DB connection after the request is handled."""- if not db.is_closed():- db.close()-- @app.after_request- def log_response_info(response):- """Log response details."""- app.logger.info(f"Response Status: {response.status}")- return responsediff --git a/prompt-service/src/unstract/prompt_service/helpers/usage.py b/prompt-service/src/unstract/prompt_service/helpers/usage.pyindex e6580fb14..eecade1bd 100644--- a/prompt-service/src/unstract/prompt_service/helpers/usage.py+++ b/prompt-service/src/unstract/prompt_service/helpers/usage.py@@ -3,7 +3,7 @@ from typing import Anyfrom flask import current_app as appfrom unstract.prompt_service.constants import DBTableV2-from unstract.prompt_service.extensions import db+from unstract.prompt_service.extensions import db, db_contextfrom unstract.prompt_service.utils.db_utils import DBUtilsfrom unstract.prompt_service.utils.env_loader import get_env_or_die@@ -34,11 +34,12 @@ class UsageHelper:logger.info("Querying usage metadata for org_id: %s, run_id: %s", org_id, run_id)- with db.execute_sql(query, (run_id, organization_uid)) as cursor:- results: list[tuple] = cursor.fetchall()- # Process results as needed- for row in results:- key, item = UsageHelper._get_key_and_item(row)+ with db_context():+ with db.execute_sql(query, (run_id, organization_uid)) as cursor:+ results: list[tuple] = cursor.fetchall()+ # Process results as needed+ for row in results:+ key, item = UsageHelper._get_key_and_item(row)# Initialize the key as an empty list if it doesn't existif key not in metadata:metadata[key] = []diff --git a/prompt-service/src/unstract/prompt_service/utils/db_utils.py b/prompt-service/src/unstract/prompt_service/utils/db_utils.pyindex f650f6187..400c540e8 100644--- a/prompt-service/src/unstract/prompt_service/utils/db_utils.py+++ b/prompt-service/src/unstract/prompt_service/utils/db_utils.py@@ -1,7 +1,7 @@from typing import Any, Optionalfrom unstract.prompt_service.constants import DBTableV2-from unstract.prompt_service.extensions import db+from unstract.prompt_service.extensions import db, db_contextfrom unstract.prompt_service.utils.env_loader import get_env_or_dieDB_SCHEMA = get_env_or_die("DB_SCHEMA", "unstract")@@ -38,9 +38,10 @@ class DBUtils:@classmethoddef execute_query(cls, query: str, params: tuple = ()) -> Any:- cursor = db.execute_sql(query, params)- result_row = cursor.fetchone()- cursor.close()- if not result_row or len(result_row) == 0:- return None- return result_row[0]+ with db_context():+ cursor = db.execute_sql(query, params)+ result_row = cursor.fetchone()+ cursor.close()+ if not result_row or len(result_row) == 0:+ return None+ return result_row[0]