我试图让用户下载我生成的xml文件。
这是我的代码:
tree.write('output.xml', encoding="utf-16")
# Pathout is the path to the output.xml
xmlFile = open(pathout, 'r')
myfile = FileWrapper(xmlFile.read())
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename='+filename
return response
当我尝试创建我的回复时,我得到了这个例外:
'\\'str\\' object has no attribute \\'read\\''
无法弄清楚我做错了什么。有什么想法吗?
编辑: 当我使用这段代码时,我没有错误,而是下载的文件是空的
tree.write('output.xml', encoding="utf-16")
xmlFile = open(pathout, 'r')
myfile = FileWrapper(xmlFile)
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename='+filename
return response
答案 0 :(得分:4)
您正在调用xmlFile.read()
- 它产生一个字符串 - 并将结果传递给FileWrapper()
,它需要一个类似于文件的可读对象。您应该将xmlFile
传递给FileWrapper
,或者根本不使用FileWrapper
,并将xmlFile.read()
的结果作为HttpResponse
正文传递。
请注意,如果您正在动态创建xml(根据您的代码段的第一行似乎就是这种情况),将其写入磁盘只是为了将其读回几行以后都浪费时间和资源以及竞争条件的潜在原因。您可能想查看https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring
答案 1 :(得分:2)
您正在读取文件并将结果字符串传递给FileWrapper,而不是传递实际的文件对象。
myfile = FileWrapper(xmlFile)
答案 2 :(得分:0)
或者从其他答案中,我建议使用Django模板系统彻底解决问题:
from django.http import HttpResponse
from django.template import Context, loader
def my_view(request):
# View code here...
t = loader.get_template('myapp/myfile.xml')
c = Context({'foo': 'bar'})
response = HttpResponse(t.render(c), content_type="application/xml")
response['Content-Disposition'] = 'attachment; filename=...'
return response
以这种方式创建一个myfile.xml
模板,用于呈现正确的xml响应,而不必处理将任何文件写入文件系统。这是更清洁和更快,因为没有其他需要确实创建xml并永久存储它。