我正在嘗試撰寫一個腳本來幫助我使用我們的 CAT 工具(Memsource)自動化一些作業。為此,我需要使用 API 上傳一些檔案。
我依賴此處提供的 Memsource API 檔案:https ://cloud.memsource.com/web/docs/api#operation/createJob
我寫了一個簡短的代碼來測驗檔案上傳,然后再讓它異步,我有一些嚴重的問題:文本檔案正確上傳,雖然上傳后文本的正文包含一些添加:
--4002a5507da490554ad71ce8591ccf69
Content-Disposition: form-data; name="file"; filename=“test.txt"
我也嘗試上傳 DOCX 檔案,但它甚至無法在 Memsource 在線編輯器中打開——我猜內容是一路修改的,但我找不到在哪里......
負責上傳的代碼如下:
def test_upload(self):
# Assemble "Memsource" header as mentioned in the API docs
Memsource_header = {
"targetLangs": ["pl"],
}
# Open the file to be uploaded and extract file name
f = open("Own/TMS_CAT/test.txt", "rb")
f_name = os.path.basename(f.name)
# Assemble the request header
header = {
"Memsource": json.dumps(Memsource_header),
"Content-Disposition": f'attachment; filename="{f_name}"',
"Authorization": f"ApiToken {self.authToken}",
"Content-Type": "application/octet-stream; charset=utf-8",
}
# Make POST request and catch results
file = {"file": f}
req = requests.post(
"https://cloud.memsource.com/web/api2/v1/projects/{project-id}/jobs",
headers=header,
files=file,
)
print(req.request.headers)
print(req.json())
請求頭:
{
"User-Agent":"python-requests/2.27.1",
"Accept-Encoding":"gzip, deflate",
"Accept":"*/*",
"Connection":"keep-alive",
"Memsource":"{\"targetLangs\": [\"pl\"]}",
"Content-Disposition":"attachment; filename=\"test.txt\"",
"Authorization":"ApiToken {secret}",
"Content-Type":"application/octet-stream; charset=utf-8",
"Content-Length":"2902"
}
以及來自 Memsource 的回應:
{
"asyncRequest":{
"action":"IMPORT_JOB",
"dateCreated":"2022-02-22T18:36:30 0000",
"id":"{id}"
},
"jobs":[
{
"workflowLevel":1,
"workflowStep":{
"uid":"{uid}",
"order":2,
"id":"{id}",
"name":"Tra"
},
"imported":false,
"dateCreated":"2022-02-22T18:36:30 0000",
"notificationIntervalInMinutes":-1,
"updateSourceDate":"None",
"dateDue":"2022-10-10T12:00:00 0000",
"targetLang":"pl",
"continuous":false,
"jobAssignedEmailTemplate":"None",
"uid":"{id}",
"status":"NEW",
"filename":"test.txt",
"sourceFileUid":"{id}",
"providers":[
]
}
],
"unsupportedFiles":[
]
}
在我看來,兩者都不錯...
我將不勝感激有關如何使這件事起作用的任何建議!:-)
uj5u.com熱心網友回復:
我設法解決了這個問題——注意到請求在請求正文中添加了一些有限的標頭,即傳入files引數的檔案內容。
我只是擺脫了它并將代碼更改如下:
# Open the file to be uploaded and extract file name
with open(
"/file.ext", "rb"
) as f:
f_name = os.path.basename(f.name)
# Assemble the request header
header = {
"Memsource": json.dumps(Memsource_header),
"Content-Disposition": f'attachment; filename="{f_name}"',
"Authorization": f"ApiToken {self.authToken}",
"Content-Type": "application/octet-stream; charset=utf-8",
}
req = requests.post(
"https://cloud.memsource.com/web/api2/v1/projects/{project-id}/jobs",
headers=header,
data=f,
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434679.html
標籤:python-3.x 休息 邮政 文档
上一篇:快速閱讀plist并處理錯誤
