-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
73 lines (62 loc) · 2.63 KB
/
app.py
File metadata and controls
73 lines (62 loc) · 2.63 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import logging
from decouple import config
from flask import jsonify
from config import create_app
from db import db
# Set up basic logging configuration
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
environment = config("CONFIG_ENV")
app = create_app(environment)
@app.teardown_request
def commit_transaction_on_teardown(exception=None):
"""Commit the transaction if there's no exception."""
if exception is None:
try:
db.session.commit()
except Exception as e:
db.session.rollback()
logging.error(f"Error occurred during commit: {str(e)}")
return (
jsonify(
{
"error": "An error occurred while saving data. Please try again later."
}
),
500,
)
else:
# Rollback after a flush if an error occurs to maintain session integrity:
# - Flush may cause errors if it violates database constraints (e.g., unique, foreign key),
# putting the session in a failed state. Further DB operations will fail until rollback.
# - SQLAlchemy treats the session as a single transaction. Without rollback, failed flushes
# leave the session in an invalid state, risking further errors on additional operations.
# - Rollback clears any "dirty" data left by failed flushes, ensuring a clean session for
# the next steps and preventing data contamination in complex workflows.
db.session.rollback() # rollback in case of any exception
logging.error(f"Error occurred during request: {str(exception)}")
return (
jsonify(
{
"error": "An unexpected error occurred. Please contact support if the issue persists."
}
),
500,
)
@app.teardown_appcontext
def shutdown_session(response, exception=None):
"""
Ensure a clean database session after each request by removing the current session.
This method closes and removes the active session after each request:
- Prevents session reuse across requests, ensuring no lingering data or connections persist.
- Helps avoid unintended side effects from shared sessions between requests and reduces
the risk of memory leaks from idle database connections.
- Promotes stability by creating a fresh session for each request, supporting better isolation
and reliability in database interactions.
:param response:
:param exception:
:return:
"""
db.session.remove()
return response