How do I serve a text file from Django?

后端 未结 3 820
情话喂你
情话喂你 2020-12-29 04:13

I am writing a Django based website, but need to serve a a simple text file. Is the correct way to so this by putting it in the static directory and bypassing Django?

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 04:49

    I agree with @luc, however another alternative is to use X-Accel-Redirect header.

    Imagine that you have to serve big protected (have to login to view it) static files. If you put the file in static directory, then it's access is open and anybody can view it. If you serve it in Django by opening the file and then serving it, there is too much IO and Django will use more RAM since it has to load the file into RAM. The solution is to have a view, which will authenticate a user against a database, however instead of returning a file, Django will add X-Accel-Redirect header to it's response. Now since Django is behind nginx, nginx will see this header and it will then serve the protected static file. That's much better because nginx is much better and much faste at serving static files compared to Django. Here are nginx docs on how to do that. You can also do a similar thing in Apache, however I don't remember the header.

提交回复
热议问题