python-o365
python-o365 copied to clipboard
How to create DriveItem (upload a file for the first time)
I couldn't figure out from source code how should I actually upload a file for the first time.
I have an interface for upload_file which would create or update the file in case of overwrite. The implementation:
def _get_drive_by_name(self, drive_name):
for drive in self._site.list_document_libraries():
if drive.name == drive_name:
return drive
def get_item(self, drive_name, path):
drive = self._get_drive_by_name(drive_name=drive_name)
if not drive:
raise NotADirectoryError(f"No drive by the name: '{drive_name}'' exists")
item = drive.get_item_by_path(path)
if not item:
raise FileNotFoundError(f"No item by the path: '{path}' exists")
if item.is_folder:
raise FileNotFoundError("Path {path} leads to a Folder item, not a File.")
return item
def upload_file(self, local_file, drive, path, overwrite=False):
item = self.get_item(drive, path)
try:
if item and not overwrite:
raise FileExistsError({"drive": drive, "path": path})
if not item.upload_file(local_file):
raise Exception("File upload unsuccessful.")
except Exception as error:
self._categorize_error(error, drive, path)
However I already need an item to call its upload_file function. But what if I'm just about the create the file? Should I create a Folder drive item first like folder = Folder(parent=drive) first? Then I can call the upload_file?
Or is there any other initializer around I haven't found?
Any Folder object has the upload_file method. Just use it.
https://github.com/O365/python-o365/blob/master/O365/drive.py#L1222