who*_*rth 14 python django django-rest-framework
我在views.py中有以下视图 -
class FilterView(generics.ListAPIView):
model = cdx_composites_csv
def get(self, request, format=None):
vendor = self.request.GET.get('vendor')
filename = self.request.GET.get('filename')
tablename = filename.replace(".","_")
model = get_model(vendor, tablename)
filedate = self.request.GET.get('filedate')
snippets = model.objects.using('markitdb').filter(Date__contains=filedate)
serializer = cdx_compositesSerializer(snippets, many=True)
if format == 'raw':
zip_file = open('C:\temp\core\files\CDX_COMPOSITES_20140626.zip', 'rb')
response = HttpResponse(zip_file, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'CDX_COMPOSITES_20140626.zip'
return response
else:
return Response(serializer.data)
Run Code Online (Sandbox Code Playgroud)
它适用于xml,json,csv,但是当我尝试使用raw时,它不会返回文件,而是提供""详细信息":"未找到""为什么会发生这种情况?
我正在点击的URL如下 -
有效的json示例 -
http://dt-rpittom:8000/testfilter/?vendor=markit&filename=cdx_composites.csv&filedate=2014-06-26&format=json
这应该返回一个zip文件供下载.
http://dt-rpittom:8000/testfilter/?vendor=markit&filename=cdx_composites.csv&filedate=2014-06-26&format=raw
who*_*rth 17
我不知道为什么我必须这样做 - 可能是Django Rest Framework内部的东西,它不允许将自定义方法放到格式上?
我只是将其更改为以下内容 -
if fileformat == 'raw':
zip_file = open('C:\temp\core\files\CDX_COMPOSITES_20140626.zip', 'rb')
response = HttpResponse(FileWrapper(zip_file), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'CDX_COMPOSITES_20140626.zip'
return response
Run Code Online (Sandbox Code Playgroud)
然后在我的URL中点击新值,它工作正常.我很想知道为什么我不能使用格式来提供文件.
尝试使用FileWrapper:
from django.core.servers.basehttp import FileWrapper
...
if format == 'raw':
zip_file = open('C:\temp\core\files\CDX_COMPOSITES_20140626.zip', 'rb')
response = HttpResponse(FileWrapper(zip_file), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'CDX_COMPOSITES_20140626.zip'
return response
...
Run Code Online (Sandbox Code Playgroud)
另外,我会用application/zip而不是application/force-download.
| 归档时间: |
|
| 查看次数: |
16808 次 |
| 最近记录: |