Opened 9 years ago

Closed 9 years ago

#26282 closed Bug (wontfix)

db.connection.is_usable throws when no connection exists yet

Reported by: Pierre Pattard Owned by: nobody
Component: Database layer (models, ORM) Version: 1.9
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

I am running a Celery long running process which periodically loses the MySQL connection. I am therefore trying to use the is_usable() method to ensure the database connection is usable or reset it. This method perfectly fits my needs as it simply returns True or False.

However, the first time I call it, as this is before there has been any connection physically opened yet (I have not made any use of any model yet), the connection does not exists and the method throws. It seems a bit clumsy because the django.db.connection itself exists, it is just the backend connection that has not been established yet.

Example:

import django
django.setup()
if django.db.connection.is_usable():
    print 'Usable!'

Throws the following:

Traceback (most recent call last):
  File "bug.py", line 4, in <module>
    if not django.db.connection.is_usable():
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 351, in is_usable
    self.connection.ping()
AttributeError: 'NoneType' object has no attribute 'ping'

May I suggest that in the MySQL backend (I have not tested with other backends), you check that the connections is not None before trying to invoke ping() on it ?

So something like:

    def is_usable(self):
        if not self.connection: 
            return False
        try:
            self.connection.ping()
        except Database.Error:
            return False
        else:
            return True

Thanks!

Pierre -- a very happy and enthusiastic Django user.

Change History (2)

comment:1 by Tim Graham, 9 years ago

is_usable() isn't a documented API so it's not well defined as to whether or not it's intended for your use case. I'm more inclined to say you should use the connection.ensure_connection() method to first guarantee that the connection exists. Modifying is_usable() would require adding if not self.connection: return False to the method for all the database backends.

comment:2 by Tim Graham, 9 years ago

Resolution: wontfix
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top