Class static attribute value shared between reques

2019-08-26 00:54发布

问题:

I have a a static class attribute that gets modified in the same http request.

class A:
  x = {}

  def fun(k,v):
    A.x[k] = v

My issue is that when your do another http request, the last value of the previous request persists.

Am using Django through Apache's mod WSGI .

How can I make the static value persists in the same request but not to another request?

回答1:

The whole point of static variables is for them to persist in the class rather than the instances used to handle a particular request. This is dangerous when using threader or event-based servers as the static variable will be shared not only with the next request but also with all requests handled in parallel.

I assume class A here is a class-based view. In that case, you can change your attribute to be an instance one instead:

class A(…):
    def __init__(self, *args, **kwargs):
        super()
        self.x = {}

    def foo(k, v):
        self.x[k] = v

As class-based views are re-instantiated for each request they serve, the value will not bleed into other requests.



回答2:

At the end of each request, clear the cache

@app.teardown_request
def teardown(exc):
    A.x = {}


回答3:

Inspired by muddyfish's answer I implemented a middleware's process_response

import A

class ClearStaticMiddleware(object):
  def process_response(self, request, response):
    A.x = {}
    return response

Thank you all for your responses.