[Fixed]-Disable caching for a view or url in django


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.

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.

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()
    return resp

That will solve your “cannot pickle a file” problem.



from django.views.decorators.cache import never_cache

def myview(request):
    # ...

Documentation is here…



You probably did a per site cache, but what you want to do now is a per view cache. The first one is easier to implement, but is only meant for the case of ‘just caching everything’. Because you want to choose for every view now, just switch to the fine grained approach. It is also very easy to use, but remember that sometimes you need to create a second view with the same contents, if you want to have the result sometimes cached and sometimes not, depending on the url.

So far to the answer to your question. But is that an answer to your problem? Why do you return files in a view? Normally static files like videos, pictures, css, flash games or whatever should be handled by the server itself (or even by a different server). And I guess, that is what you want to do in that view. Is that correct? The reason for not letting django do this is, because starting django and letting django do its thing also eats a lot of resoruces and time. You don’t feel that, when you are the only user in your test environment. But when you want to scale to some thousand users or more, then this kind of stuff becomes very nasty. Also from a logical point of view it does not seem smart, to let a program handle files without changing them, when the normal job of the program is to generate or change HTML according to a state of your data and a user-request. It’s like letting your accountant do the programming work. While he might be able to do it, you probably want somebody else do it and let the accountant take care of your books.

Leave a comment