Я пытаюсь прочитать файл XLSX в Sharepoint, который подается из формы Excel. Я использую Python 3.x для написания сценария для этого.
Я пытаюсь создать решение для сбора пользовательских комментариев для некоторых наших процессов, которые в настоящее время обрабатываются с помощью общих файлов Excel на сетевых дисках, иэто очень грязный результат. Я нашел несколько статей о SO и других источниках, которые указывают, что мне нужно пройти аутентификацию с Sharepoint, и пытаюсь заставить это работать в приведенном ниже коде.
Я импортирую следующие библиотеки ->
from office365.runtime.auth.authentication_context import
AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
И у меня есть еще один раздел, в котором вводятся мои учетные данные из зашифрованного файла. Я проверил переменные, которые заполняют (имя пользователя, пароль) и подтвердил, что они верны.
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Authentication successful")
response = File.open_binary(ctx, url)
#save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start
#read excel file and each sheet into pandas dataframe
df = pd.read_excel(bytes_file_obj, sheetname = 'Form1')
Я ожидаю, что соединение будет работать, и заполню свой DF из листа в excel - но получаюследующее сообщение об ошибке - которое заставило меня сначала думать, что мои учетные данные не были введены должным образом, но они есть. Я также являюсь владельцем папки, к которой я пытаюсь получить доступ, поэтому у меня нет проблем с правами доступа к моим учетным данным.
An error occurred while retrieving token: AADSTS90023: Invalid STS
request.
An error occurred while retrieving auth cookies
-------------------------------------------------------------------------
--
TypeError Traceback (most recent call
last)
<ipython-input-7-90f58cf903a0> in <module>
32 web = ctx.web
33 ctx.load(web)
---> 34 ctx.execute_query()
35 print("Authentication successful")
36
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\client_runtime_context.py in
execute_query(self)
36
37 def execute_query(self):
---> 38 self.pending_request.execute_query()
39
40 def add_query(self, query, result_object=None):
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\client_request.py in execute_query(self, query,
result_object)
25 if query:
26 return self.execute_single_query(query,
result_object)
---> 27 return self.execute_pending_queries()
28
29 def execute_pending_queries(self):
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\client_request.py in
execute_pending_queries(self)
31 for query in self.__queries:
32 request = self.build_request(query)
---> 33 response = self.execute_request_direct(request)
34 self.process_payload_json(query, response)
35 finally:
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\client_request.py in
execute_request_direct(self, request_options)
102 def execute_request_direct(self, request_options):
103 """Execute client request"""
--> 104 self.context.authenticate_request(request_options)
105 if request_options.method == HttpMethod.Post:
106 from office365.sharepoint.client_context import
ClientContext
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\client_runtime_context.py in
authenticate_request(self, request)
14
15 def authenticate_request(self, request):
---> 16 self.__auth_context.authenticate_request(request)
17
18 @property
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\auth\authentication_context.py in
authenticate_request(self, request_options)
33 """Authenticate request"""
34 if isinstance(self.provider, SamlTokenProvider):
---> 35 request_options.set_header('Cookie',
self.provider.get_authentication_cookie())
36 elif isinstance(self.provider, ACSTokenProvider) or
isinstance(self.provider, OAuthTokenProvider):
37 request_options.set_header('Authorization',
self.provider.get_authorization_header())
C:\ProgramData\Anaconda3\lib\site-
packages\office365\runtime\auth\saml_token_provider.py in
get_authentication_cookie(self)
67
68 logger.debug_secrets("self.FedAuth: %s\nself.rtFa: %s",
self.FedAuth, self.rtFa)
---> 69 return 'FedAuth=' + self.FedAuth + '; rtFa=' + self.rtFa
70
71 def get_last_error(self):
TypeError: can only concatenate str (not "NoneType") to str