Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

/Users/myself/Developer/us/www/static/files/apple-app-site-association

What am I doing wrong here?

like image 438
qarthandso Avatar asked Aug 17 '16 15:08

qarthandso


People also ask

How do I add content to a JSON file?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do you write JSON data to a file in Python?

Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.


1 Answers

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:
        data=myfile.read()
    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

  • Reading and writing files
  • Managing files with Django
like image 94
Emile Bergeron Avatar answered Oct 23 '22 14:10

Emile Bergeron