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

Viewed 182

I have this interesting issue. I am using the IIS+FastCgi+Django setup to serve queries. Initially, I was hoping for concurrent execution but there is one component X that doesn't allow its multiple invocation due to apparent failure in its license checking code when called parallely. To make sure that only 1 instance of django runs, I am planning to do the following:

  1. IIS: It doesn't have anything to do with concurrency directly as far as I checked. I might be wrong.
  2. FastCGI module in IIS:

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: Now this component X takes around 1-2 second to load itself, so i can't put its loading code inside POST view function. I am planning to put it in apps.py inside a class which extends from AppConfig of django.apps just like people load machine learning models. This way it will only be loaded once when FASTCGI worker will load django app codebase in memory.

The problem is after 200 request, when fast cgi recycles or destroys? the loaded django codebase, I need to destroy the component X instance too. However, i am not well aware regarding this aspect.

The way this component X (which is a windows application) is loaded is:

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

To destroy this component, official docs says to do this:

X.close()

Where to put this X.close() code in django? Also, feel free to correct me if I am thinking wrong.

Edit: Bounty added

1 Answers

Permit concurrency

You can use the lock mechanisms to permit unique access to the resource and permit concurrent access to the rest of you site:

import threading
lock = threading.Lock()

def foo():
    with lock:
        bar()

Here you can find some documentation about thread synchronization in python: Thread Synchronization Mechanisms in Python

Close the component

To close the component as point out in comments by Daniel Butler you can use a class and a Singleton:

a = ClassA()

class ClassA():
    self.x_instance = None

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

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