[DB] Postgres와 Django의 Connection 관리

Postgresql에서 Connection 🐘🔌

select count(*), state from pg_catalog.pg_stat_activity group by 2;
count | state
-------+------------------------------
7 | active
32 | idle
22 | idle in transaction
4 | idle in transaction(aborted)
(4 rows)
show statement_timeout;
# 설정된 명령어 timeout 시간 조회
Alter database [db_name] set statement_timeout = 60000;
set statement_timeout = 30000;
show idle_in_transaction_session_timeout;alter database [db_name] set idle_in_transaction_session_timeout = 60000;
set idle_in_transaction_session_timeout = 60000;

Django에서 Connection

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '5432',
'OPTIONS': {
'CONN_MAX_AGE': '60',
}
}
}
## django/db/backends/base/base.py  row 174def connect(self):
"""Connects to the database. Assumes that the connection is
closed."""
# Check for invalid configurations.
self.check_settings()
# In case the previous connection was closed while in an atomic block
self.in_atomic_block = False
self.savepoint_ids = []
self.needs_rollback = False
# Reset parameters defining when to close the connection
max_age = self.settings_dict['CONN_MAX_AGE']
self.close_at = None if max_age is None else time.time() + max_age
self.closed_in_transaction = False
## django/db/__init__.py row 60
# Register an event to reset transaction state and close connections past
# their lifetime.
def close_old_connections(**kwargs):
for conn in connections.all():
conn.close_if_unusable_or_obsolete()
signals.request_started.connect(close_old_connections)
signals.request_finished.connect(close_old_connections)
## django/db/backends/base/base.py row 502
def close_if_unusable_or_obsolete(self):
"""
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
"""
if self.connection is not None:
# If the application didn't restore the original autocommit setting,
# don't take chances, drop the connection.
if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
self.close()
return
# If an exception other than DataError or IntegrityError occurred
# since the last commit / rollback, check if the connection works.
if self.errors_occurred:
if self.is_usable():
self.errors_occurred = False
else:
self.close()
return
if self.close_at is not None and time.time() >= self.close_at:
self.close()
return
from django import db
db.connections.close_all()

--

--

Blog https://chrisjune.dev Work for www.29cm.co.kr

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store