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

标签 python django iis fastcgi

我有这个有趣的问题。我正在使用 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 View 函数中。我打算将它放在 apps.py 中的一个类中,该类从 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 的评论指出关闭组件你可以使用一个类和一个单例:

a = ClassA()

class ClassA():
    self.x_instance = None

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

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

关于python - 如何在 django+fastcgi+IIS 设置中销毁资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62838775/

相关文章:

python - 编写此 if 语句的更好方法?

python - 在python中将 float 写入csv——截断错误

django - 将 Bootstrap 和自定义 css 应用于 django 中的 {{form}} 元素

python - django 如何解释 CommaSeparatedIntegerField 'max_length' 字段选项?

database - django null 和空字符串

python - py.warning : Just one line, 但调试需要堆栈跟踪

powershell - foreach循环中的 “if any”是否存在?

amazon-web-services - 如何在运行Windows的ElasticBeanstalk环境中启用CloudWatchLogs?

.net - 服务器管理器问题

python - 在 NumPy 数组中沿轴获取 N 个最大值和索引