Should a database connection be opened only once in a django app or once for every user within views.py?

StackOverflow https://stackoverflow.com/questions/10994755

  •  14-06-2021
  •  | 
  •  

Question

I'm working on my first Django project.

I need to connect to a pre-existing key value store (in this case it is Kyoto Tycoon) for a one off task. i.e. I am not talking about the main database used by django.

Currently, I have something that works, but I don't know if what I'm doing is sensible/optimal.

views.py

from django.http import HttpResponse
from pykt import KyotoTycoon

def get_from_kv(user_input):

    kt=KyotoTycoon()
    kt.open('127.0.0.1',1978)

    # some code to define the required key
    # my_key = ...

    my_value = kt.get(my_key)

    kt.close()

    return HttpResponse(my_value)

i.e. it opens a new connection to the database every time a user makes a query, then closes the connection again after it has finished.

Or, would something like this be better?

views.py

from django.http import HttpResponse
from pykt import KyotoTycoon

kt=KyotoTycoon()
kt.open('127.0.0.1',1978)

def get_from_kv(user_input):

    # some code to define the required key
    # my_key = ...

    my_value = kt.get(my_key)

    return HttpResponse(my_value)

In the second approach, will Django only open the connection once when the app is first started? i.e. will all users share the same connection?

Which approach is best?

Was it helpful?

Solution

Opening a connection when it is required is likely to be the better solution. Otherwise, there is the potential that the connection is no longer open. Thus, you would need to test that the connection is still open, and restart it if it isn't before continuing anyway.

This means you could run the queries within a context manager block, which would auto-close the connection for you, even if an unhanded exception occurs.

Alternatively, you could have a pool of connections, and just grab one that is not currently in use (I don't know if this would be an issue in this case).

It all depends just how expensive creating connections is, and if it makes sense to be able to re-use them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top