DEVOPS ADO POST request for attachments to backlog (Python) - Error uploading attachment: I/O operation on closed file

Eamonn Hegarty 0 Reputation points
2024-06-26T08:47:21.1733333+00:00

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

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
37,262 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. SnehaAgrawal-MSFT 19,676 Reputation points
    2024-06-26T09:40:30.68+00:00

    @Eamonn Hegarty

    Thanks for the question and using Microsoft Q&A platform.

    Azure DevOps is currently not supported in the Microsoft Q&A platform; the supported products are listed over here https://docs.microsoft.com/en-us/answers/products

    The Azure DevOps team and community are active and answering questions on https://developercommunity.visualstudio.com/spaces/21/index.html Please post your question there and experts will guide you.

    You can also ask for help on Stack overflow: https://stackoverflow.com/questions/tagged/azure-devops or request for support here : https://azure.microsoft.com/en-us/support/devops/

    This will assist you with a faster reply to your query.

    0 comments No comments