禁用Django中视图或URL的缓存

禁用Django中视图或URL的缓存

问题描述:

在django中,我写了一个只返回文件的视图,现在我遇到了问题,因为memcache试图缓存该视图,换句话说, TypeError:无法腌制文件对象。

In django, I wrote a view that simply returns a file, and now I am having problems because memcache is trying to cache that view, and in it's words, "TypeError: can't pickle file objects".

由于我实际上确实需要使用该视图返回文件(我本质上已经为此视图创建了基于文件的缓存),所以我需要做的就是以某种方式使它成为内存缓存我不能或不会尝试缓存视图。

Since I actually do need to return files with this view (I've essentially made a file-based cache for this view), what I need to do is somehow make it so memcache can't or won't try to cache the view.

我认为可以通过两种方式完成。首先,阻止视图被缓存(装饰器在这里很有意义),其次,阻止URL缓存。

I figure this can be done in two ways. First, block the view from being cached (a decorator would make sense here), and second, block the URL from being cached.

似乎都不可能,而且似乎也没有其他人遇到这个问题,至少在公共互联网上没有。帮帮我?

Neither seems to be possible, and nobody else seems to have run into this problem, at least not on the public interwebs. Help?

更新:我已经尝试过@never_cache装饰器,甚至认为它可以正常工作,但是虽然这样设置了标头,所以其他人不会缓存东西,而我的本地计算机仍然会缓存。

Update: I've tried the @never_cache decorator, and even thought it was working, but while that sets the headers so other people won't cache things, my local machine still does.

返回真实的文件对象从一个角度看来听起来有些不对劲。我可以看到返回文件的内容,并将这些内容输入到HttpResponse对象中。如果我对您的理解正确,则说明您正在将该视图的结果缓存到文件中。像这样的东西:

Returning a real, actual file object from a view sounds like something is wrong. I can see returning the contents of a file, feeding those contents into an HttpResponse object. If I understand you correctly, you're caching the results of this view into a file. Something like this:

def myview(request):
    file = open('somefile.txt','r')
    return file    # This isn't gonna work. You need to return an HttpRequest object.

我猜想,如果您完全在settings.py中关闭缓存,则腌制一个文件对象将变成视图必须返回一个http响应对象。

I'm guessing that if you turned caching off entirely in settings.py, your "can't pickle a file object" would turn into a "view must return an http response object."

如果我对正在发生的事情处在正确的轨道上,那么这里是

If I'm on the right track with what's going on, then here are a couple of ideas.

您提到要为此视图创建基于文件的缓存。您确定要这样做,而不只是使用memcached吗?

You mentioned you're making a file-based cache for this one view. You sure you want to do that instead of just using memcached?

如果您确实想要文件,请执行以下操作:

If you really do want a file, then do something like:

def myview(request):
    file = open('somefile.txt','r')
    contents = file.read()
    resp = HttpRespnse()
    resp.write(contents)
    file.close()
    return resp

这将解决您的无法腌制文件问题。

That will solve your "cannot pickle a file" problem.