使用Python请求库下载Jasper报告

时间:2016-07-18 14:31:12

标签: python python-requests jasperserver

我正在使用jasper服务器报告API(rest_v2)。

在api下执行以生成报告并获取requestsID和exportID。

http://localhost:8080/jasperserver/rest_v2/reportExecutions

{
  "status": "ready",
  "totalPages": 0,
  "requestId": "d0ae905c-1538-4e40-b5ad-c145f521707c",
  "reportURI": "/reports/Invoices/COD",
  "exports": [
    {
      "id": "49f47112-4698-4398-9ed8-a62d552a7aa5",
      "status": "ready",
      "outputResource": {
        "contentType": "application/pdf",
        "fileName": "COD.pdf",
        "outputFinal": true
      }
    }
  ]
}

上面的api工作正常(你可以看到输出)

现在我将使用下面的api下载生成的报告。

http://localhost:8080/jasperserver/rest_v2/reportExecutions/d0ae90c-1538-4e40-b5ad-c145f521707c/exports/49f47112-4698-4398-9ed8-a62d552a7aa5/outputResource

在Postman中,我提供了三个标题

"Authorization": "Basic " + token
"Accept": "application/json",
"Content-Type": "application/xml"

并且能够下载报告。

现在我尝试使用python-requests库做同样的事情。我在下载api中得到的响应是

{
  "message": "Resource d0ae95c-1538-4e40-b5ad-c145f521707c not found.",
  "errorCode": "resource.not.found",
  "parameters": [
    "d0ae95c-1538-4e40-b5ad-c145f521707c"
  ]
}

下面是完整的代码

data = """
        <reportExecutionRequest>
          ...
        </reportExecutionRequest>
        """

url = "http://localhost:8080/jasperserver/rest_v2/reportExecutions"

headers = {
    "Authorization": "Basic " + token,
    "Accept": "application/json",
    "Content-Type": "application/xml",
}

response = requests.post(url, data=data, headers=headers)
data = response.json()
request_id = data.get("requestId")
export_id = data.get("exports")[0].get("id")

# Till here working fine

report_url = "http://localhost:8080/jasperserver/rest_v2/reportExecutions/{request_id}/exports/{export_id}/outputResource".format(request_id=request_id, export_id=export_id)

headers = {
    "Authorization": "Basic " + token,
    "Accept": "application/json",
    "Content-Type": "application/xml",
}

report_resp = requests.get(report_url, headers=headers)

print report_resp.json()

#{
#    "message": "Resource d0ae95c-1538-4e40-b5ad-c145f521707c not found.",
#    "errorCode": "resource.not.found",
#    "parameters": [
#    "d0ae95c-1538-4e40-b5ad-c145f521707c"
#    ]
#}

PS:您可以确定令牌。我在邮递员中测试过,它工作正常。

1 个答案:

答案 0 :(得分:2)

确定。我通过传递cookie解决了它

report_resp = requests.get(report_url, headers=headers, cookies=response.cookies)