Class static attribute value shared between reques

2019-08-26 00:10发布

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?

3条回答
叛逆
2楼-- · 2019-08-26 00:49

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.

查看更多
戒情不戒烟
3楼-- · 2019-08-26 00:57

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.

查看更多
Root(大扎)
4楼-- · 2019-08-26 01:03

At the end of each request, clear the cache

@app.teardown_request
def teardown(exc):
    A.x = {}
查看更多
登录 后发表回答