Idle database connections in Django

南楼画角 提交于 2019-12-08 03:33:23

问题


In Django, how do I make my code recover from a database connection which is dead ? This is the scenario:

# requests enters view handler

# executes code which does some synchronous tasks without any database interaction for 15min.

# first database activity in this request after 15min.
try:
   o, created = act_details.objects.get_or_create(id=1) # this line fails because of a dead database connection.

except Exception as e:
   logger.error(e) # ORA-03114: not connected to ORACLE

Assuming I handle the exception, is there a way to put things back on track by creating a new database connection in the exception block ?

My issue is similar to Recover from dead database connection in Django but different because the connections I use are entirely framework managed.

This issue happens only when the remote server/network/firewall drops idle connections.


回答1:


Normally as a developer you shouldn't be exposed to the internals of Django that way.

As Django establishes a connection on each request it has an opportunity to both pool connections and persist connections.

Connections time out eventially anyway so you need a mechanism to provide you with database connections.

A pool pattern is really what you need and depending on your situation there are some packages that offer Connection pooling for Oracle: https://pypi.python.org/pypi/django-oraclepool

I haven't tried that to tell you if it works though.

UPDATE

Alternativelly you can access the underlying database cursor:

from django.db import connections

try:
   o, created = act_details.objects.get_or_create(id=1) # this line fails because of a dead database connection.

except Exception as e:
  logger.error(e) # ORA-03114: not connected to ORACLE
  conn = connections['oracle']
  if conn.connection is None: # Attempt to get it again 
     with connection.cursor() as c:         
        c.execute("SELECT * from act_details WHERE id = %s" % [self.id])

This way though you lose all the benefits of the Django ORM but its a workaround.



来源:https://stackoverflow.com/questions/30024004/idle-database-connections-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!