请求之间的Django持久性API连接 [英] Django persistent API connections between requests

查看:60
本文介绍了请求之间的Django持久性API连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有很多内部和外部API,基本上每个请求都会调用这些API.这意味着需要建立许多与这些API的连接.有没有一种方法可以创建一个可以在请求之间共享的持久连接对象?

So I have a lot of internal and external APIs that are called on basically each request. This means that there's a lot of setting up connections to these APIs. Is there a way of creating a persistent connection object that can be shared between requests?

所以我想替换:

def a(request):
    c = api.connect()
    c.call_function()

使用:

def b(request):
    // use existing connection object from earlier request
    c.call_function()

有什么想法吗?

我也不知道会有多大的收益,但是我不介意在有了第一个解决方案后就进行一些基准测试.

I'm also not sure how big the gain would be but I don't mind doing some benchmarking once I have a first solution.

推荐答案

非常简单

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

使用同一工作程序/服务器进程的任何请求都将共享此连接.因此,如果您有三名工作人员为您的应用程序提供服务,那么您最多将拥有三个连接.

This connection would be shared by any request using the same worker/server process. So if you have three workers serving your application you would have at most three connections.

我担心连接可能会开始超时.因此,您需要提防这一点.也许有一个检查连接状态的函数,如果连接仍然良好,则将其返回,或者如果连接已过期,则创建一个新的函数.

I would worry that the connections might start timing out. So you would want to guard against that. Perhaps by having a function that checked the state of the connection, returned it if it was still good, or creating a new one if it had expired.

为什么可以使用以下示例进行说明:

Why this works can be illustrated with the following example:

>>> a = 1
>>> def add(b):
...     print a + b
... 
>>> add(2)
3

请注意,如果不使用global关键字,则无法修改连接

Note that you can't modify the connection without using the global keyword

>>> def change(c):
...     a = c
...     print a
... 
>>> change(4)
4
>>> print a
1

比较:

>>> a = 1
>>> def change(d):
...     global a
...     a = d
...     print a
... 
>>> change(5)
5
>>> print a
5
>>> 

如果要在不同的工作程序/进程之间共享api连接,将变得有些棘手.即不要打扰.

If you want to share the api connection between different workers/processes it becomes a bit trickier. i.e don't bother.

这篇关于请求之间的Django持久性API连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆