|
| 1 | +import json |
| 2 | +from typing import IO, AnyStr, Callable |
| 3 | + |
| 4 | +from typing_extensions import Self |
| 5 | + |
| 6 | +from office365.runtime.client_result import ClientResult |
| 7 | +from office365.sharepoint.files.system_object_type import FileSystemObjectType |
| 8 | +from office365.sharepoint.listitems.collection import ListItemCollection |
| 9 | +from office365.sharepoint.listitems.listitem import ListItem |
| 10 | +from office365.sharepoint.lists.list import List |
| 11 | + |
| 12 | + |
| 13 | +class ListExporter(object): |
| 14 | + |
| 15 | + @staticmethod |
| 16 | + def export( |
| 17 | + source_list, destination_file, include_content=False, item_exported=None |
| 18 | + ): |
| 19 | + # type: (List, IO, bool, Callable[[ListItem], None]) -> Self |
| 20 | + """Exports SharePoint List""" |
| 21 | + import zipfile |
| 22 | + |
| 23 | + def _append_file(name, data): |
| 24 | + with zipfile.ZipFile( |
| 25 | + destination_file.name, "a", zipfile.ZIP_DEFLATED |
| 26 | + ) as zf: |
| 27 | + zf.writestr(name, data) |
| 28 | + |
| 29 | + def _download_content(list_item): |
| 30 | + # type: (ListItem) -> None |
| 31 | + def _after_downloaded(result): |
| 32 | + # type: (ClientResult[AnyStr]) -> None |
| 33 | + item_path = list_item.properties["FileRef"].replace( |
| 34 | + source_list.root_folder.serverRelativeUrl, "" |
| 35 | + ) |
| 36 | + _append_file(item_path, result.value) |
| 37 | + |
| 38 | + list_item.file.get_content().after_execute(_after_downloaded) |
| 39 | + |
| 40 | + def _export_items(items): |
| 41 | + # type: (ListItemCollection) -> None |
| 42 | + |
| 43 | + for item in items: |
| 44 | + item_path = str(item.id) + ".json" |
| 45 | + |
| 46 | + if item.file_system_object_type == FileSystemObjectType.File: |
| 47 | + _append_file(item_path, json.dumps(item.to_json())) |
| 48 | + |
| 49 | + if include_content: |
| 50 | + _download_content(item) |
| 51 | + |
| 52 | + if callable(item_exported): |
| 53 | + item_exported(item) |
| 54 | + |
| 55 | + def _get_items(): |
| 56 | + ( |
| 57 | + source_list.items.select( |
| 58 | + [ |
| 59 | + "*", |
| 60 | + "Id", |
| 61 | + "FileRef", |
| 62 | + "FileDirRef", |
| 63 | + "FileLeafRef", |
| 64 | + "FileSystemObjectType", |
| 65 | + ] |
| 66 | + ) |
| 67 | + .get() |
| 68 | + .paged(page_loaded=_export_items) |
| 69 | + ) |
| 70 | + |
| 71 | + source_list.ensure_properties(["SchemaXml", "RootFolder"], _get_items) |
| 72 | + |
| 73 | + return source_list |
0 commit comments