[Answer]-Serve raw files as text/plain on Django server

1👍

It seems that you’re storing the full static URL for these KML files, but then in your serve_file method you’re trying to open that URL as if it was a local file path, and read and serve the content.

Rather than trying to fix this, why not just redirect to the static URL?

res = KmlModel.objects.get(state__state__exact=state)
return HttpResponseRedirect(res.KML_File.url)

Edit Actually, I realise that your KML_File field is presumably a models.FileField. in which case, you can open it directly with res.KML.File.open(), so no need to pass the URL to your serve_file method.

Also, don’t forget you need to return the result of calling serve_file.

0👍

Is open() the standard Python open()? If so this operates on files, not URLs (although I was unable to get the same exception when opening a URL with open()). Try instead:

import urllib2

def serve_file(url):
    response = HttpResponse(mimetype="text/plain")
    for line in urllib2.urlopen(url):
        response.write(line)
    return response

You could also try redirecting to that URL, however, I am not sure that the correct MIME type will be set for the Content-type response header.

👤mhawke

Leave a comment