Skip to main content
 首页 » 编程设计

python之无法为 xml 下载创建 HttpResponse,Django

2025年05月04日36qlqwjy

我正在尝试让用户下载我生成的 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 

请您参考如下方法:

您正在调用 xmlFile.read() - 它产生一个字符串 - 并将结果传递给 FileWrapper() ,它需要一个可读的类文件对象。您应该将 xmlFile 传递给 FileWrapper,或者根本不使用 FileWrapper 并传递 xmlFile.read()< 的结果 作为你的 HttpResponse 主体。

请注意,如果您正在动态创建 xml(根据您的代码片段的第一行,这似乎是这种情况),将其写入磁盘只是为了在几行之后读回它既浪费时间和资源,又竞争条件的潜在原因。你也许想看看 https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring