Skip to content

Commit fe8d087

Browse files
committed
Support pathlike objects in upload util
Also switch to inbuilt filename encode helper, since it accepts paths
1 parent d6c206a commit fe8d087

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

slack_sdk/web/internal_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -317,8 +317,8 @@ def _to_v2_file_upload_item(upload_file: Dict[str, Any]) -> Dict[str, Optional[A
317317
content = upload_file.get("content")
318318
data: Optional[bytes] = None
319319
if file is not None:
320-
if isinstance(file, str): # filepath
321-
with open(file.encode("utf-8", "ignore"), "rb") as readable:
320+
if isinstance(file, (str, os.PathLike)): # filepath
321+
with open(os.fsencode(file), "rb") as readable:
322322
data = readable.read()
323323
elif isinstance(file, bytes):
324324
data = file
@@ -339,8 +339,8 @@ def _to_v2_file_upload_item(upload_file: Dict[str, Any]) -> Dict[str, Optional[A
339339
filename = upload_file.get("filename")
340340
if filename is None:
341341
# use the local filename if filename is missing
342-
if isinstance(file, str):
343-
filename = file.split(os.path.sep)[-1]
342+
if isinstance(file, (str, os.PathLike)):
343+
filename = os.fspath(file).split(os.path.sep)[-1]
344344
else:
345345
filename = "Uploaded file"
346346

tests/slack_sdk/web/test_internal_utils.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import unittest
33
from io import BytesIO
4+
from pathlib import Path
45
from typing import Dict, Sequence, Union
56

67
import pytest
@@ -101,6 +102,13 @@ def test_files_upload_v2_issue_1356(self):
101102
file_io_item = _to_v2_file_upload_item({"file": file_io, "filename": "foo.txt"})
102103
assert file_io_item.get("filename") == "foo.txt"
103104

105+
def test_files_upload_v2_paths(self):
106+
filepath = "tests/slack_sdk/web/test_internal_utils.py"
107+
upload_item_str = _to_v2_file_upload_item({"file": filepath})
108+
upload_item_path = _to_v2_file_upload_item({"file": Path(filepath)})
109+
assert upload_item_path == upload_item_str
110+
assert upload_item_str.get("filename") == "test_internal_utils.py"
111+
104112
def test_next_cursor_is_present(self):
105113
assert _next_cursor_is_present({"next_cursor": "next-page"}) is True
106114
assert _next_cursor_is_present({"next_cursor": ""}) is False

0 commit comments

Comments
 (0)