Class static attribute value shared between requests

旧巷老猫 提交于 2019-12-12 00:15:00

问题


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.



来源:https://stackoverflow.com/questions/31937746/class-static-attribute-value-shared-between-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!