Skip to content

Commit 7afd588

Browse files
committed
fix: modernize upload_file with str | PathLike | IOBase, update example
1 parent e819327 commit 7afd588

2 files changed

Lines changed: 13 additions & 17 deletions

File tree

examples/onedrive/files/upload_download.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,15 @@
99
from office365.graph_client import GraphClient
1010
from tests import test_client_id, test_password, test_tenant, test_username
1111

12-
FILE_NAME = "Financial Sample.xlsx"
13-
LOCAL_PATH = Path("../../data") / FILE_NAME
12+
file_name = "Financial Sample.xlsx"
13+
local_path = Path("../../data") / file_name
1414

1515
client = GraphClient(tenant=test_tenant).with_username_and_password(test_client_id, test_username, test_password)
1616

17-
with open(LOCAL_PATH, "rb") as f:
18-
uploaded = client.me.drive.root.upload_file(f).execute_query()
17+
uploaded = client.me.drive.root.upload_file(local_path).execute_query()
1918

20-
download_path = Path(__file__).parent / FILE_NAME
19+
download_path = Path(__file__).parent / file_name
2120
with open(download_path, "wb") as f:
2221
uploaded.download(f).execute_query()
2322

24-
print(f"Uploaded and downloaded: {FILE_NAME} ({download_path.stat().st_size:,} bytes)")
23+
print(f"Uploaded and downloaded: {file_name} ({download_path.stat().st_size:,} bytes)")

office365/onedrive/driveitems/driveItem.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import os
44
from datetime import datetime
55
from functools import partial
6+
from io import IOBase
7+
from os import PathLike
68
from os.path import isfile, join
79
from typing import IO, AnyStr, Callable
810

@@ -383,17 +385,12 @@ def _modify_query(request: RequestOptions) -> None:
383385
self.context.add_query(qry).before_execute(_modify_query)
384386
return return_type
385387

386-
def upload_file(self, path_or_file: str | IO) -> DriveItem:
387-
"""Uploads a file"""
388-
if isinstance(path_or_file, IO):
389-
content = path_or_file.read()
390-
name = os.path.basename(path_or_file.name)
391-
return self.upload(name, content)
392-
else:
393-
with open(path_or_file, "rb") as f:
394-
content = f.read()
395-
name = os.path.basename(path_or_file)
396-
return self.upload(name, content)
388+
def upload_file(self, path_or_file: str | PathLike | IOBase) -> DriveItem:
389+
"""Uploads a file (up to ~4MB; use resumable_upload for larger files)."""
390+
if isinstance(path_or_file, IOBase):
391+
return self.upload(os.path.basename(path_or_file.name), path_or_file.read())
392+
with open(path_or_file, "rb") as f:
393+
return self.upload(os.path.basename(str(path_or_file)), f.read())
397394

398395
def upload_folder(self, path: str, file_uploaded: Callable[["DriveItem"], None] | None = None) -> DriveItem:
399396
"""Uploads a folder"""

0 commit comments

Comments
 (0)