0

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?

4

1 回答 1

1

在需要时打开连接可能是更好的解决方案。否则,连接可能不再打开。因此,您需要测试连接是否仍然打开,如果没有,则重新启动它,然后再继续。

这意味着您可以在上下文管理器块中运行查询,即使发生未经处理的异常,它也会为您自动关闭连接。

或者,您可以有一个连接池,然后只获取一个当前未使用的连接(我不知道在这种情况下这是否会成为问题)。

这一切都取决于创建连接的成本,以及能够重用它们是否有意义。

于 2012-06-12T10:33:44.577 回答