Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serve a text file from Django?

Tags:

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?

like image 930
smithy Avatar asked Jan 24 '13 13:01

smithy


People also ask

How do I view a text file in Django?

If you want to pass the content of the text file to your template. html add it to the context variable and access it in your template with {{ file_content }} . Keep in mind that a web server like nginx or apache would normally take care of serving static files for performance reasons.

How do I run Collectstatic in Django?

Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.


2 Answers

If the file is static (not generated by the django app) then you can put it in the static directory.

If the content of this file is generated by Django then you can return it in a HttpResponse with text/plain as mimetype.

content = 'any string generated by django' return HttpResponse(content, content_type='text/plain') 

You can also give a name to the file by setting the Content-Disposition of the response.

filename = "my-file.txt" content = 'any string generated by django' response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response 
like image 80
luc Avatar answered Oct 13 '22 03:10

luc


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.

like image 30
miki725 Avatar answered Oct 13 '22 01:10

miki725