|
1 | 1 | """ |
2 | | -Upload a file to OneDrive, then download it. |
| 2 | +Upload a file to OneDrive, then download it back. |
3 | 3 |
|
4 | | -The most common file operation — upload and download content. |
5 | | -
|
6 | | -Requires delegated permission ``Files.ReadWrite``. |
7 | | -
|
8 | | -https://learn.microsoft.com/en-us/graph/api/driveitem-put-content |
9 | | -https://learn.microsoft.com/en-us/graph/api/driveitem-get-content |
| 4 | +Requires delegated permission Files.ReadWrite. |
10 | 5 | """ |
11 | 6 |
|
12 | 7 | import os |
13 | | -import tempfile |
| 8 | +from pathlib import Path |
14 | 9 |
|
15 | 10 | from office365.graph_client import GraphClient |
16 | 11 | from tests import test_client_id, test_password, test_tenant, test_username |
17 | 12 |
|
| 13 | +FILE_NAME = "Financial Sample.xlsx" |
| 14 | +LOCAL_PATH = Path(__file__).parent.parent.parent.parent / "tests" / "data" / FILE_NAME |
| 15 | + |
18 | 16 | client = GraphClient(tenant=test_tenant).with_username_and_password(test_client_id, test_username, test_password) |
19 | 17 |
|
20 | | -# Upload a file to OneDrive root |
21 | | -content = b"Hello, OneDrive!" |
22 | | -uploaded = client.me.drive.root.upload("hello.txt", content).execute_query() |
23 | | -print(f"Uploaded: {uploaded.name} (id: {uploaded.id})") |
24 | | - |
25 | | -# Download it back |
26 | | -with tempfile.TemporaryDirectory() as path: |
27 | | - local_path = os.path.join(path, "hello.txt") |
28 | | - with open(local_path, "wb") as f: |
29 | | - uploaded.download(f).execute_query() |
30 | | - print(f"Downloaded to: {local_path} (size: {os.path.getsize(local_path)} bytes)") |
| 18 | +with open(LOCAL_PATH, "rb") as f: |
| 19 | + uploaded = client.me.drive.root.upload_file(f).execute_query() |
| 20 | + |
| 21 | +download_path = os.path.join(os.path.dirname(__file__), FILE_NAME) |
| 22 | +with open(download_path, "wb") as f: |
| 23 | + uploaded.download(f).execute_query() |
| 24 | + |
| 25 | +print(f"Uploaded and downloaded: {FILE_NAME} ({os.path.getsize(download_path):,} bytes)") |
0 commit comments