qarthandso qarthandso - 1 year ago 96
JSON Question

How to put a JSON file's content in a response

I have a file on my computer that I'm trying to serve up as JSON from a django view.

def serve(request):
file = os.path.join(BASE_DIR, 'static', 'files', 'apple-app-site-association')
response = HttpResponse(content=file)
response['Content-Type'] = 'application/json'

What I get back is the path to the file when navigating to the URL


What am I doing wrong here?

Answer Source

os.path.join returns a string, it's why you get a path in the content of the response. You need to read the file at that path first.

For a static file

If the file is static and on disk, you could just return it using the webserver and avoid using python and django at all. If the file needs authenticating to be downloaded, you could still handle that with django, and return a X-Sendfile header (this is dependant on the webserver).

Serving static files is a job for a webserver, Nginx and Apache are really good at this, while Python and Django are tools to handle application logic.

Simplest way to read a file

def serve(request):
    path = os.path.join(BASE_DIR, 'static', 'files', 'apple-app-site-association')
    with open(path , 'r') as myfile:
    response = HttpResponse(content=data)
    response['Content-Type'] = 'application/json'

This is inspired by How do I read a text file into a string variable in Python

For a more advanced solution

See dhke's answer on StreamingHttpResponse.

Additional information

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download