1

I have a text file in the static folder in my project root.

I'd like to serve it so I've created:

@csrf_exempt
def display_text(request):

    content = 
    return HttpResponse(content, content_type='text/plain; charset=utf8')

How do I set the path to the textfile, or how do I read it in to 'content', so that I can display it.

user1592380
  • 34,265
  • 92
  • 284
  • 515
  • If it's in the static folder, why ask Django to serve it at all? It will be served by whatever is serving the rest of your static files, like the JS and CSS. – Daniel Roseman Jun 11 '15 at 21:21
  • Thanks for looking at it Daniel, I'm planning to deploy this to Heroku, where I don't have complete control of the environment. I assumed that I couldn't serve directly. Is there a way to do this? – user1592380 Jun 11 '15 at 22:30
  • I don't see why you need any special control. As I say, if it's in your static folder it will get served in exactly the same way as your images, stylesheets and JavaScript files. – Daniel Roseman Jun 11 '15 at 22:54

1 Answers1

5

Have a look at this question that lets Apache handle the file delivery with mod_xsendfile.

If you insist on having Django itself delivering the file, you could do the following:

from django.http import StreamingHttpResponse

@csrf_exempt
def display_text(request):
    content = open('/your/file', 'r').read()
    response = StreamingHttpResponse(content)
    response['Content-Type'] = 'text/plain; charset=utf8'
    return response
Community
  • 1
  • 1
mimo
  • 2,469
  • 2
  • 28
  • 49
  • Thanks for showing me how to do it. I ended up following https://devcenter.heroku.com/articles/django-assets, which showed me how to serve the assets on heroku – user1592380 Jun 12 '15 at 16:06