简体   繁体   中英

Serving a django static text file

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM