在视图中返回 json 文件
在视图中,我创建新文件:
sys.stdout = open(backup_name, 'w')
call_command('dumpdata')
现在如何将此文件返回给用户?
我尝试将 HttpResponse 中的 mimetype 更改为“application/json”,但如何将文件内容添加到响应中?
或者也许还有其他方式返回文件?
。
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?
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我知道有点晚了,但我发现这是一个有用的起点,所以我认为其他人也可以从我的发现中受益。
对于小文件,如果将 json 文件放在模板文件夹中,django 可以找到它,并且可以使用 render_to_response 返回它:
我发现这对于某些浏览器上的大型数据集来说是有问题的。我会收到错误
现有连接被远程主机强制关闭
。另一种方法解决了这个问题。首先,您必须创建文件的完整路径。使用 PROJECT_ROOT 变量(由 settings.py 中的 PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) 定义)。要访问此方法和 os 方法,您必须在views.py 中
导入settings, os
。一旦你有了这个文件位置,你就可以使用下面的代码返回它:我发现这对于非常大的文件来说也很有效。
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
: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 mustimport settings, os
in views.py. Once you have this file location you can return it using the code below:I found this worked well for even very large files.
好的,我已经有了:
将文件保存在光盘上后,我打开它进行读取并设置文件名作为响应。
有人有其他想法吗?
OK I have it:
After saving file on disc I open it for reading and set file name in response.
Anyone has another idea?
我试图将字典作为 json 文件返回。这是我的解决方案:
I was trying to return a dictionary as a json file. Here is my solution:
只需复制/链接/调用与模型序列化相关的转储数据代码,并将其直接转储到响应中,这样就可以避免权限问题和文件系统污染。内容处置和 mimetype 仍然适用。
无论如何请记住,转储数据可能是一个漫长的过程,因此您可能会遇到超时。
Just copy/link/call the dumpdata code related to model serialization, and dump it directly into the response, so you avoid permission problems and filesystem pollution. Content-disposition and mimetype still applies.
Remember anyway that dumpdata can be a lenghty process, so you are exposed to timeouts.
我的最终解决方案是(感谢 saverio):
My final solution is (thanks to saverio):