简体   繁体   中英

How to persist data between requests using Django

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.

There are a lot of different solutions to this. Depending on your datasize you could store the data in the sessions object, the apps object, of even open up a small database like an sqlite or an in memory structure eg redis like these guys did:

Django: how to store a lot of data between requests if I don't have a database

Here's a getting started on accessing session data:

https://docs.djangoproject.com/en/3.0/topics/http/sessions/

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM