black laptop computer on brown wooden table

Office365-REST-Python-Clientを使用したOneDriveへの1GBファイルのアップロード

クラウドストレージのOneDriveにファイルを自動的にアップロードする方法について話します。特にPythonを使ったアプローチに焦点を当てます。この記事は、開発者、データサイエンティスト、またはOneDriveを活用して効率を上げたい人向けに書かれています。

前提条件

このチュートリアルでは、Python 3.6以上がインストールされていることを前提とします。また、必要なPythonパッケージをインストールするためにpipも必要です。これらがまだインストールされていない場合は、公式のPythonウェブサイトからダウンロードしてください。

必要なパッケージ

まず最初に、このプロジェクトで必要となるPythonパッケージをインストールしましょう。今回はOffice365のREST APIクライアントライブラリを使用します。このパッケージは、OneDriveとの連携を容易にします。以下のコマンドを実行してパッケージをインストールしましょう:

pip install Office365-REST-Python-Client

この操作はスクリプトを実行する前に行ってください。

Pythonスクリプトの作成

以下に、Pythonを使用してOneDriveにファイルをアップロードするための基本的なスクリプトを提供します。

(インデントが崩れてしまってすみません。。)

from office365.runtime.auth.user_credential import UserCredential
from office365.runtime.client_request_exception import ClientRequestException
from office365.onedrive.driveitems.drive_item import DriveItem
from office365.graph_client import GraphClient
from office365.runtime.auth.authentication_context import AuthenticationContext
import os


def get_onedrive_context_using_user():
tenant = "xxxxxxxxxx"
authority_url = f"https://login.microsoftonline.com/{tenant}"
client_id = "xxxxxxxxxx"
client_secret = "password"

context_auth = AuthenticationContext(authority_url)
context_auth.acquire_token_for_app(client_id, client_secret)

client = GraphClient(context_auth)
return client


def create_onedrive_directory(client, dir_name: str):
"""
Creates a folder in the OneDrive directory.
"""
if dir_name:
drive_item = DriveItem(client)
drive_item.name = dir_name
drive_item.folder = {"childCount": 0}
return client.me.drive.root.children.add(drive_item)


local_path = "1G.csv"
dir_name = 'test-tsukada-dir-hoge'
chunk_size = 50000000

def print_upload_progress(range_pos):
print("{0} bytes uploaded".format(range_pos))

try:
client = get_onedrive_context_using_user()
create_onedrive_directory(client, dir_name)
remote_drive = client.me.drive.root.get_by_path(dir_name)

with open(local_path, 'rb') as f:
remote_drive.resumable_upload(f, chunk_size=chunk_size, chunk_uploaded=print_upload_progress).get().execute_query()
print(f"File {local_path} has been uploaded")
except ClientRequestException as ex:
print(ex)

このスクリプトは OneDrive 上のルートにフォルダを作成し、指定したファイルをそのフォルダにアップロードします。アップロードの進行状況はコールバック関数print_upload_progress を用いて表示します。

ただし、このコードは Azure AD のアプリ登録で取得した client_id と client_secret を使用していますので、それぞれ適切な値に置き換えてください。また、Azure AD のテナントIDも必要となります。

スクリプトの実行

スクリプトを実行するには、以下のコマンドをターミナルまたはコマンドプロンプトから実行します:

python upload_to_onedrive.py

これで、指定したファイルがOneDriveに自動的にアップロードされます!

まとめ

Pythonを使用してOneDriveにファイルを自動アップロードする方法について解説しました。この方法は、定期的なバックアップ、大量のファイルの移行、または一般的なファイルの管理など、さまざまなシナリオで役立ちます。