I have this really strange bug where we have a form that users can submit bugs and this form hits and endpoint that will take the information and attachments (pdf etc) and send to our backlog as a work item in ado. The code works locally but in our envs we get this error based on the logs I added to figure out what was wrong:
Error uploading attachment: I/O operation on closed file.
The code that gets this error (No error running locally):
if document["files"]:
for file in document["files"]:
workitem_id = r.json()["id"]
attachment_data = file.file.read()
r = requests.post(
f"{self.base_url}/_apis/wit/attachments?fileName={file.filename}&api-version={self.api_version}",
data=attachment_data,
auth=("", self.pat),
headers={"Content-Type": "application/octet-stream"},
)
update_data = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": r.json()["url"],
"attributes": {"comment": "Spec for the work"},
},
}
]
r = requests.request(
method="PATCH",
url=f"{self.base_url}/_apis/wit/workitems/{workitem_id}?api-version= {self.api_version}",
json=update_data,
headers={"Content-Type": "application/json-patch+json"},
auth=("", self.pat),
)
So I tried adding logs which got me the error shown and based on some documentation I tried using the with key word:
if document["files"]:
for file in document["files"]:
try:
workitem_id = r.json()["id"]
with file.file as attachment_file:
attachment_data = attachment_file.read()
r = requests.post(
f"{self.base_url}/_apis/wit/attachments?fileName={file.filename}&api- version={self.api_version}",
data=attachment_data,
auth=("", self.pat),
headers={"Content-Type": "application/octet-stream"},
)
logger.info(
f"Uploading {file.filename} to backlog attachments returned status code: {r.status_code}, response: {r.text}"
)
update_data = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": r.json()["url"],
"attributes": {"comment": "Spec for the work"},
},
}
]
r = requests.request(
method="PATCH",
url=f"{self.base_url}/_apis/wit/workitems/{workitem_id}?api-version={self.api_version}",
json=update_data,
headers={"Content-Type": "application/json-patch+json"},
auth=("", self.pat),
)
logger.info(
f"Patching '{file.filename}' to item '{document['title']}' returned status code: {r.status_code}, response: {r.text}"
)
except Exception as e:
logger.error(f"Error uploading attachment: {e}")
But that got this error: Error uploading attachment: Cannot enter context with closed file