[Fixed]-Open cassandra connection only once in Django

1đź‘Ť

For a “one connection per Django process” scheme, basically, what you want is

  • a connection proxy class (which you already have) with a “lazy” connection behaviour (doesn’t connect until someone tries to use the connection),
  • a module-global instance of this class that other packages can import, and
  • a way to ensure the connection gets properly closed (which cassandra requires for proper operation)

This last point well be the main difficulty as none of the available options (mainly atexit.register() and the __del__(self) method) are 101% reliable. Implementing __del__(self) on your connection proxy might be the most reliable still, just beware of circular depencies (http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python might be a good read here).

Also note that a “one single connection per django process” mean your connections must be totally thread-safe, as you usually will have many threads per Django process (depending on your wsgi container configuration).

Another solution – if thread-safety is an issue – might be to have a single connection per request…

Leave a comment