请求之间的Django持久API连接

olo*_*fom 4 python django persistent-connection

所以我有很多内部和外部 API,基本上每个请求都会调用它们。这意味着有很多设置与这些 API 的连接。有没有办法创建一个可以在请求之间共享的持久连接对象?

所以我想替换:

def a(request):
    c = api.connect()
    c.call_function()
Run Code Online (Sandbox Code Playgroud)

和:

def b(request):
    // use existing connection object from earlier request
    c.call_function()
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

我也不确定收益会有多大,但是一旦我有了第一个解决方案,我不介意做一些基准测试。

ayc*_*dee 5

真的很简单

conn = api.connect() # This line is run only once when the process starts and the module is loaded 

def view(request):
    conn.call_function() # This line is run every time a request is received
Run Code Online (Sandbox Code Playgroud)

此连接将由使用相同工作/服务器进程的任何请求共享。因此,如果您有 3 个工作人员为您的应用程序服务,您将最多拥有三个连接。

我担心连接可能会开始超时。所以你会想要防范这种情况。也许通过一个函数来检查连接的状态,如果它仍然良好则返回它,或者如果它已经过期则创建一个新的。

可以通过以下示例说明为什么会这样:

>>> a = 1
>>> def add(b):
...     print a + b
... 
>>> add(2)
3
Run Code Online (Sandbox Code Playgroud)

请注意,不使用 global 关键字不能修改连接

>>> def change(c):
...     a = c
...     print a
... 
>>> change(4)
4
>>> print a
1
Run Code Online (Sandbox Code Playgroud)

相比:

>>> a = 1
>>> def change(d):
...     global a
...     a = d
...     print a
... 
>>> change(5)
5
>>> print a
5
>>> 
Run Code Online (Sandbox Code Playgroud)

如果您想在不同的工作人员/进程之间共享 api 连接,它会变得有点棘手。即不要打扰。