Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return json file in a view

In a view I create new file with:

sys.stdout = open(backup_name, 'w')
call_command('dumpdata')

How can I now return this file to user?

I tried to change mimetype in HttpResponse to 'application/json' but how can I add file content to response?

Or maybe there is other way to return file?

.

like image 365
szaman Avatar asked Nov 15 '25 06:11

szaman


2 Answers

I know it's a bit late, but I found this a useful starting point so I thought others could benefit from what I found too.

For a small file, if you place the json file in a template folder, django can find it and you can return it with render_to_response:

return render_to_response(data_file,mimetype='application/json')

I found this to be problematic for large datasets on certain browsers. I would get the error An existing connection was forcibly closed by the remote host. An alternative approach fixed this.

First you must create full path to your file. Use the PROJECT_ROOT variable (defined by PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) in settings.py). To access this and the os methods you must import settings, os in views.py. Once you have this file location you can return it using the code below:

backup_path = os.path.join(settings.PROJECT_ROOT, "templates", "json_dumps", "large_file.json")
return HttpResponse(open(backup_path, 'r'),content_type = 'application/json; charset=utf8')

I found this worked well for even very large files.

like image 94
turtlemonvh Avatar answered Nov 17 '25 23:11

turtlemonvh


OK I have it:

response = HttpResponse(open(backup_path, "r"), mimetype='application/json', )
response['Content-Disposition'] = "filename=%s" % backup_name"

After saving file on disc I open it for reading and set file name in response.

Anyone has another idea?

like image 35
szaman Avatar answered Nov 17 '25 23:11

szaman