Better database connection cleanup.

This commit is contained in:
SergeantPanda 2025-10-16 14:22:19 -05:00
parent 4df2f79bcf
commit 9b2ebf169b
4 changed files with 37 additions and 10 deletions

View file

@ -33,14 +33,8 @@ class BaseConfig:
settings = CoreSettings.get_proxy_settings()
cls._proxy_settings_cache = settings
cls._proxy_settings_cache_time = now
# Close the connection after reading settings to avoid keeping it open
try:
connection.close()
except Exception:
pass
return settings
except Exception:
# Return defaults if database query fails
return {
@ -50,6 +44,13 @@ class BaseConfig:
"channel_shutdown_delay": 0,
"channel_init_grace_period": 5,
}
finally:
# Always close the connection after reading settings
try:
connection.close()
except Exception:
pass
@classmethod
def get_redis_chunk_ttl(cls):

View file

@ -597,6 +597,8 @@ class ChannelService:
@staticmethod
def _update_stream_stats_in_db(stream_id, **stats):
"""Update stream stats in database"""
from django.db import connection
try:
from apps.channels.models import Stream
from django.utils import timezone
@ -622,6 +624,13 @@ class ChannelService:
except Exception as e:
logger.error(f"Error updating stream stats in database for stream {stream_id}: {e}")
return False
finally:
# Always close database connection after update
try:
connection.close()
except Exception:
pass
# Helper methods for Redis operations

View file

@ -930,6 +930,7 @@ class StreamManager:
# Import both models for proper resource management
from apps.channels.models import Stream, Channel
from django.db import connection
# Update stream profile if we're switching streams
if self.current_stream_id and stream_id and self.current_stream_id != stream_id:
@ -947,8 +948,16 @@ class StreamManager:
logger.debug(f"Updated m3u profile for channel {self.channel_id} to use profile from stream {stream_id}")
else:
logger.warning(f"Failed to update stream profile for channel {self.channel_id}")
except Exception as e:
logger.error(f"Error updating stream profile for channel {self.channel_id}: {e}")
finally:
# Always close database connection after profile update
try:
connection.close()
except Exception:
pass
# CRITICAL: Set a flag to prevent immediate reconnection with old URL
self.url_switching = True