Skip to content

Commit 445d375

Browse files
authored
Close the file descriptor for add_attachment (#957)
* 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
1 parent 760d584 commit 445d375

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

jira/client.py

+30-15
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
Type,
3636
TypeVar,
3737
Union,
38+
cast,
3839
no_type_check,
3940
)
4041
from urllib.parse import urlparse
@@ -845,8 +846,11 @@ def add_attachment(
845846
Returns:
846847
Attachment
847848
"""
849+
close_attachment = False
848850
if isinstance(attachment, str):
849851
attachment: BufferedReader = open(attachment, "rb") # type: ignore
852+
attachment = cast(BufferedReader, attachment)
853+
close_attachment = True
850854
elif isinstance(attachment, BufferedReader) and attachment.mode != "rb":
851855
self.log.warning(
852856
"%s was not opened in 'rb' mode, attaching file may fail."
@@ -861,13 +865,17 @@ def add_attachment(
861865

862866
if "MultipartEncoder" not in globals():
863867
method = "old"
864-
r = self._session.post(
865-
url,
866-
files={"file": (fname, attachment, "application/octet-stream")},
867-
headers=CaseInsensitiveDict(
868-
{"content-type": None, "X-Atlassian-Token": "no-check"}
869-
),
870-
)
868+
try:
869+
r = self._session.post(
870+
url,
871+
files={"file": (fname, attachment, "application/octet-stream")},
872+
headers=CaseInsensitiveDict(
873+
{"content-type": None, "X-Atlassian-Token": "no-check"}
874+
),
875+
)
876+
finally:
877+
if close_attachment:
878+
attachment.close()
871879
else:
872880
method = "MultipartEncoder"
873881

@@ -878,14 +886,21 @@ def file_stream() -> MultipartEncoder:
878886
)
879887

880888
m = file_stream()
881-
r = self._session.post(
882-
url,
883-
data=m,
884-
headers=CaseInsensitiveDict(
885-
{"content-type": m.content_type, "X-Atlassian-Token": "no-check"}
886-
),
887-
retry_data=file_stream,
888-
)
889+
try:
890+
r = self._session.post(
891+
url,
892+
data=m,
893+
headers=CaseInsensitiveDict(
894+
{
895+
"content-type": m.content_type,
896+
"X-Atlassian-Token": "no-check",
897+
}
898+
),
899+
retry_data=file_stream,
900+
)
901+
finally:
902+
if close_attachment:
903+
attachment.close()
889904

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

0 commit comments

Comments
 (0)