python - 通过 REST API 下载 .docx 文件
问题描述
我正在尝试使用 Adobe 的 REST API 导出 PDF > DOCX: https ://documentcloud.adobe.com/document-services/index.html#post-exportPDF
我面临的问题是无法在本地正确保存它(它已损坏)。我找到了另一个具有类似目标的线程,但那里的解决方案对我不起作用。以下是我脚本的相关部分:
url = "https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D"
payload = {}
payload['contentAnalyzerRequests'] = json.dumps(
{
"cpf:engine": {
"repo:assetId": "urn:aaid:cpf:Service-26c7fda2890b44ad9a82714682e35888"
},
"cpf:inputs": {
"params": {
"cpf:inline": {
"targetFormat": "docx"
}
},
"documentIn": {
"dc:format": "application/pdf",
"cpf:location": "InputFile"
}
},
"cpf:outputs": {
"documentOut": {
"dc:format": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"cpf:location": docx_filename,
}
}
}
)
myfile = {'InputFile': open(filename,'rb')}
response = requests.request("POST", url, headers=headers, data=payload, files=myfile)
location = response.headers['location']
...
polling here to make sure export is complete
...
if response.status_code == 200:
print('Export complete, saving file locally.')
write_to_file(docx_filename, response)
def write_to_file(filename, response):
with open(filename, 'wb') as f:
for chunk in response.iter_content(1024 * 1024):
f.write(chunk)
我认为问题(或至少是解决方案的线索)是在 response.content 的乞求时的以下文本:
--Boundary_357737_1222103332_1635257304781
Content-Type: application/json
Content-Disposition: form-data; name="contentAnalyzerResponse"
{"cpf:inputs":{"params":{"cpf:inline":{"targetFormat":"docx"}},"documentIn":{"dc:format":"application/pdf","cpf:location":"InputFile"}},"cpf:engine":{"repo:assetId":"urn:aaid:cpf:Service-26c7fda2890b44ad9a82714682e35888"},"cpf:status":{"completed":true,"type":"","status":200},"cpf:outputs":{"documentOut":{"cpf:location":"output/pdf_test.docx","dc:format":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}}}
--Boundary_357737_1222103332_1635257304781
Content-Type: application/octet-stream
Content-Disposition: form-data; name="output/pdf_test.docx"
... actual byte content starts here...
为什么要发送这个?我是否将内容错误地写入文件(我也尝试 f.write(response.content)
过,结果相同)。我应该向 Adobe 发送不同的请求吗?
解决方案
额外的文本实际上是为了让服务器可以一次发送多个文件,请参阅https://stackoverflow.com/a/20321259。基本上,您得到的响应是两个文件:一个名为 的 JSON 文件contentAnalyzerResponse
和一个名为output/pdf_test.docx
.
您可能可以使用parse_form_data
from解析文件werkzeug.formparser
,如此处所示,我之前已经成功完成过,但我不确定如何让它与多个文件一起使用。
关于您关于剥离内容的问题:根据我上面所说的,是的,像您正在做的那样剥离它是完全可以的。
注意:我建议在文本编辑器中打开文件并检查文件的最后,以确保没有任何额外--Boundary...
的内容需要删除。
推荐阅读
- ansible - 流浪者抛出错误“剧本”在客人上不存在
- java - 如何在将字符串作为参数传递的类中使用字符串作为变量
- altair - 如何根据下拉列表为图表选择数据?
- php - move_uploaded_file 函数保存到不同目录文件夹问题
- php - 将 [audio] 转换为核心 php 中的标记
- arrays - 尝试将数据加载到数组中时数组未定义
- c# - 使用 C# window 获取 SQL 所有 DB 大小
- python - 在 Python (Boto3) 中打开 S3 存储桶中的 .docx 文件
- postgresql - 如果约束已存在于数据库中,django 迁移的 AlterField 是否会导致问题?
- python - 在列表中查找重复项并绘制正方形 - turtle/python