如何在 django+fastcgi+IIS 设置中销毁资源?

How to destroy resource in a django+fastcgi+IIS setup?

我有这个有趣的问题。我正在使用 IIS+FastCgi+Django 设置来提供查询服务。最初,我希望并发执行,但有一个组件 X 不允许多次调用,因为并行调用时其许可证检查代码明显失败。为了确保只有 1 个 django 实例运行,我计划执行以下操作:

  1. IIS:据我检查,它与并发没有任何直接关系。我可能是错的。
  2. IIS 中的 FastCGI 模块:

Max instances: 1 ( I think this means that fastcgi will only load 1 codebase of django app in memory.)

Instance Max Request: 200 (This will make sure that after my above codebase of django app in memory handles 200 requests sequentially, it destroys itself and restart.) Why this recycling is even necessary?

Queue Length: 1000 (This will create a backlog of incoming requests and even if they are coming from multiple sources, it will make sure that they aren't rejected immediately)

  1. Django:现在这个组件 X 需要大约 1-2 秒来加载自身,所以我不能将它的加载代码放在 POST 视图函数中。我打算将它放在 apps.py 中的 class 中,它从 django.apps 的 AppConfig 扩展而来,就像人们加载机器学习模型一样。这样,当 FASTCGI worker 将 django 应用程序代码库加载到内存中时,它只会加载一次。

问题是在200个请求之后,fast cgi什么时候回收或者销毁?加载的 django 代码库,我也需要销毁组件 X 实例。不过这方面我不是很清楚

加载此组件 X(这是一个 windows 应用程序)的方式是:

X = library.sdk("name") // this basically opens a connection to application's com object.

要销毁这个组件,官方文档说要这样做:

X.close()

将这个 X.close() 代码放在 django 的什么地方?另外,如果我想错了,请随时纠正我。

编辑:增加赏金

允许并发

您可以使用锁定机制来允许对资源的唯一访问并允许对站点的其余部分进行并发访问:

import threading
lock = threading.Lock()

def foo():
    with lock:
        bar()

在这里你可以找到一些关于python线程同步的文档: Thread Synchronization Mechanisms in Python

关闭组件

要关闭 Daniel Butler 评论中指出的组件,您可以使用 class 和单例:

a = ClassA()

class ClassA():
    self.x_instance = None

    def __init__(self):
       self.x_instances = library.sdk("name")

    def __del__(self):
        self.x_instances.Close()