OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter eamohego
  • Start date Start date
E

eamohego

Guest
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):

Code:
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:

Code:
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
<p>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:</p>
<p>Error uploading attachment: I/O operation on closed file.</p>
<p>The code that gets this error (No error running locally):</p>
<pre><code>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),
)
</code></pre>
<p>So I tried adding logs which got me the error shown and based on some documentation I tried using the with key word:</p>
<pre><code>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}")
</code></pre>
<p>But that got this error:
Error uploading attachment: Cannot enter context with closed file</p>
 

Latest posts

А
Replies
0
Views
1
Али-Мухаммад Закарьяев
А
M
Replies
0
Views
1
Marcos R. Guevara
M
M
Replies
0
Views
1
Marcos R. Guevara
M
Top