How to persist data between requests using Django

Felipe :

I have a Django app that is running inside a Kubernetes cluster and I want to implement a prestop hook for it. The idea here is that whenever the prestop hook is called, the pod / container will fail the readiness probe check so it won't receive any new requests before being shut down by the cluster. In this case, both the readiness probe and the prestop hook are api endpoints in my app: /readiness and /prestop.

Also, to fail the readiness probe I must return a code that is higher that 400 whenever the /readiness is called.

So my question is, how can I store a state that says that I should return 400 in the readiness probe after the prestop hook has been called?. Please note that I should return 400 only for the pod for which the prestop hook was called, the other pods / containers should continue functioning normally. So I am looking for a way to keep track a single pod's / container's state.

I've made a very silly test to see if I could keep the state of a counter between requests:

class ReadinessProbeView(View):
    def __init__(self):
        self.count = 0

    def get(self, request):
        result = {}

        self.count = self.count + 1
        result["healthy"] = True
        result["count"] = self.count
        return JsonResponse(result, status=200)

However, no matter how many times I call this function, count = 1, so the state is not being maintained between requests.

Felipe :

I followed @coderanger's advice and used a global variable. My readiness probe is working as expected now.

Here is my example updated:

count = 0
class ReadinessProbeView(View):
    def get(self, request):
        result = {}

        global count
        count = count + 1
        result["healthy"] = True
        result["count"] = count
        return JsonResponse(result, status=200)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31717&siteId=1