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

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật