Вот начальный код для подключения к точке доступа через Python, а также для доступа к списку файлов, папок и отдельному содержимому файла Sharepoint. Вы можете использовать его в соответствии с вашими потребностями.
Обратите внимание, что этот метод работает для сайтов publi c Sharepoint, доступных через inte rnet. Для сайтов Sharepoint с ограниченным доступом организации, которые размещены на внутреннем сервере anet, я не тестировал этот код.
Вам придется немного изменить ссылку на файл Sharepoint, поскольку вы не можете напрямую получить доступ к Файл Sharepoint в Python с использованием URL-адреса этого файла, скопированного из веб-браузера.
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
####inputs########
# This will be the URL that points to your sharepoint site.
# Make sure you change only the parts of the link that start with "Your"
url_shrpt = 'https://YourOrganisation.sharepoint.com/sites/YourSharepointSiteName'
username_shrpt = 'YourUsername'
password_shrpt = 'YourPassword'
folder_url_shrpt = '/sites/YourSharepointSiteName/Shared%20Documents/YourSharepointFolderName/'
#######################
###Authentication###For authenticating into your sharepoint site###
ctx_auth = AuthenticationContext(url_shrpt)
if ctx_auth.acquire_token_for_user(username_shrpt, password_shrpt):
ctx = ClientContext(url_shrpt, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print('Authenticated into sharepoint as: ',web.properties['Title'])
else:
print(ctx_auth.get_last_error())
############################
####Function for extracting the file names of a folder in sharepoint###
###If you want to extract the folder names instead of file names, you have to change "sub_folders = folder.files" to "sub_folders = folder.folders" in the below function
global print_folder_contents
def print_folder_contents(ctx, folder_url):
try:
folder = ctx.web.get_folder_by_server_relative_url(folder_url)
fold_names = []
sub_folders = folder.files #Replace files with folders for getting list of folders
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders:
fold_names.append(s_folder.properties["Name"])
return fold_names
except Exception as e:
print('Problem printing out library contents: ', e)
######################################################
# Call the function by giving your folder URL as input
filelist_shrpt=print_folder_contents(ctx,folder_url_shrpt)
#Print the list of files present in the folder
print(filelist_shrpt)
Теперь, когда мы распечатали список файлов, представленных в определенной папке в Sharepoint, ниже приведен код для доступа к содержимому файла определенного файла и сохранения его на локальном диске, который знает имя файла и путь в Sharepoint.
#Specify the URL of the sharepoint file. Remember to change only the the parts of the link that start with "Your"
file_url_shrpt = '/sites/YourSharepointSiteName/Shared%20Documents/YourSharepointFolderName/YourSharepointFileName'
#Load the sharepoint file content to "response" variable
response = File.open_binary(ctx, file_url_shrpt)
#Save the file to your offline path
with open("Your_Offline_File_Path", 'wb') as output_file:
output_file.write(response.content)
Вы можете обратиться к следующим ссылкам для подключения к SQL серверу и хранение содержимого в таблицах: Подключение к серверу Microsoft SQL с использованием Python
https://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/