Idle database connections in Django

旧街凉风 提交于 2019-12-08 12:52:29

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.

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