Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close the file descriptor for add_attachment #957

Merged
merged 4 commits into from
May 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 30 additions & 15 deletions jira/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
Type,
TypeVar,
Union,
cast,
no_type_check,
)
from urllib.parse import urlparse
Expand Down Expand Up @@ -849,8 +850,11 @@ def add_attachment(
Returns:
Attachment
"""
close_attachment = False
if isinstance(attachment, str):
attachment: BufferedReader = open(attachment, "rb") # type: ignore
attachment = cast(BufferedReader, attachment)
close_attachment = True
elif isinstance(attachment, BufferedReader) and attachment.mode != "rb":
self.log.warning(
"%s was not opened in 'rb' mode, attaching file may fail."
Expand All @@ -865,13 +869,17 @@ def add_attachment(

if "MultipartEncoder" not in globals():
method = "old"
r = self._session.post(
url,
files={"file": (fname, attachment, "application/octet-stream")},
headers=CaseInsensitiveDict(
{"content-type": None, "X-Atlassian-Token": "no-check"}
),
)
try:
r = self._session.post(
url,
files={"file": (fname, attachment, "application/octet-stream")},
headers=CaseInsensitiveDict(
{"content-type": None, "X-Atlassian-Token": "no-check"}
),
)
finally:
if close_attachment:
attachment.close()
else:
method = "MultipartEncoder"

Expand All @@ -882,14 +890,21 @@ def file_stream() -> MultipartEncoder:
)

m = file_stream()
r = self._session.post(
url,
data=m,
headers=CaseInsensitiveDict(
{"content-type": m.content_type, "X-Atlassian-Token": "no-check"}
),
retry_data=file_stream,
)
try:
r = self._session.post(
url,
data=m,
headers=CaseInsensitiveDict(
{
"content-type": m.content_type,
"X-Atlassian-Token": "no-check",
}
),
retry_data=file_stream,
)
finally:
if close_attachment:
attachment.close()

js: Union[Dict[str, Any], List[Dict[str, Any]]] = json_loads(r)
if not js or not isinstance(js, Iterable):
Expand Down