Skip to content

Commit

Permalink
Close the file descriptor for add_attachment (#957)
Browse files Browse the repository at this point in the history
* Close the file descriptor for add_attachment

If the attachment is string, the add_attachment function creates a
file descriptor then forget to close it. The patch closes the file
descriptor after the post action.

* Pass a correct type for the variable

* Convert type earliy

* Refine code format
  • Loading branch information
yen3 committed May 18, 2021
1 parent 760d584 commit 445d375
Showing 1 changed file with 30 additions and 15 deletions.
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 @@ -845,8 +846,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 @@ -861,13 +865,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 @@ -878,14 +886,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

0 comments on commit 445d375

Please sign in to comment.