【问题标题】:Serve web service response to download as file [duplicate]提供 Web 服务响应以下载为文件 [重复]
【发布时间】:2016-03-23 04:45:11
【问题描述】:

我有一个模板,用于呈现来自 Web 服务的响应。

def XMLResponseView9request):
    ...
    with open(archivo_request,"r") as archivo:
         request_data = archivo.read()

    headers = {'Content-type':'text/xml'}
    data_response = requests.post(target_url, data=request_data, headers=headers)
    jdato = xmltodict.parse(data_response.content)
    data_xml = data_response.text
    data_template = json.dumps(jdato)

    return render_to_response('response.html',
                              {'data':data_template,'dataxml':data_xml},
                              context_instance=RequestContext(request))

除了呈现响应之外,我还希望将响应作为要下载的文件(xml 或 txt)提供。

我尝试将响应作为文本(变量:data_xml)传递并通过一个简单的 javascript 函数提供,但文件为空或只有一行“[object Object]”。

可以从 DJANGO 视图将响应作为文件提供,而不是将文本传递给模板。

提前致谢

【问题讨论】:

  • 所以你希望xml文件被浏览器下载,对吧?
  • 是的,我希望能够选择下载文件或只读取模板中的文件,因为有时响应有很多信息或很少信息。响应取决于先前为用户选择的 WS

标签: python django web-services django-views


【解决方案1】:

要使文件可下载,您只需更改一个 HTTP 标头 Content-Disposition。

def some_view(response):
    xmlFile = open(pathout, 'r')
    myfile = FileWrapper(xmlFile)
    response = HttpResponse(myfile, content_type='application/xml')
    response['Content-Disposition'] = 'attachment; filename='+filename
    return response

【讨论】:

  • 我有一个疑问。我需要创建其他视图来传递响应并使其能够下载,或者我可以使用我实际使用的视图。按照您的建议如何传递变量和模板名称。
  • 所以你想在页面上显示它并提供下载按钮?
  • 是的。我尝试将数据传递给模板,但是当我下载文件时只说[object object]
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2012-06-15
  • 2011-08-09
  • 1970-01-01
相关资源
最近更新 更多