Office365-rest-python-client: Not able to use it for Python 3

Created on 4 Jul 2017  ·  24Comments  ·  Source: vgrem/Office365-REST-Python-Client

Is there an issue with python 3?

bug enhancement

Most helpful comment

@vic-by A recent commit fixes the problem : https://github.com/vgrem/Office365-REST-Python-Client/commit/90731f
Note that at this time, this commit has not yet been pushed on pypi. So if you do a pip install Office365-REST-Python-Client you won't get that code. Installing from git will : pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

All 24 comments

Hello,

it should be compatible with both versions of Python: 2 and 3, but let me verify it. Will get back to you.

Hi Thanks for the prompt reply.
Below is the error i am getting
`---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in ()
1 import json
2
----> 3 from office365.runtime.auth.authentication_context import AuthenticationContext
4 from office365.runtime.client_request import ClientRequest
5 from office365.runtime.utilities.request_options import RequestOptions

ModuleNotFoundError: No module named 'office365'`

And Yes, I have pip install the moduel :)

Hi, I have written code to get the information by only using Requests module. and I can get the FedAuth and rtFa cookies successfully. However, it throws an error Forbidden when i try to get the siteUsers.
Can you please help in this?
`import requests

url="https://login.microsoftonline.com/extSTS.srf"
headers = {'content-type': 'application/json'}
TopLevelUrl='https://XXXX.sharepoint.com'
path='C:\PSR\PythonFiles\SharePointOnlineXML.txt'

filecontent = open(path,'r')
SharepointOnlineAuth = filecontent.read()
SharepointOnlineAuth=SharepointOnlineAuth.format('[email protected]','Password',TopLevelUrl)

Let's make call to get the Token in order to get the cookies

response=requests.post(url,data=SharepointOnlineAuth,headers=headers)
s=str(response.content)
Start = [pos for pos in range(len(s)) if s[pos:].startswith('')][0]
Finish= [pos for pos in range(len(s)) if s[pos:].startswith('
')][0]
LoginResponse=s[Start+40:Finish]

Now, Lets fetch the cookies to make Call to SharePoint Online

url=TopLevelUrl+'/_forms/default.aspx?wa=wsignin1.0'
headers = {'content-type': 'application/x-www-form-urlencoded'}
response=requests.post(url,data=LoginResponse,headers=headers)

Calling the Sharepoint REST Api using cookies obtained from above Call

url=TopLevelUrl+'/_api/web/siteusers'
print(url)
_Fedauth='FedAuth={}'.format(response.cookies['FedAuth'])
_rtFa='rtFa={}'.format(response.cookies['rtFa'])
_FinalDict={'Cookie':_Fedauth+','+_rtFa}

headers = {'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
headers.update(_FinalDict)

print(headers)

response=requests.get(url,headers=headers)
print (response)`

getting an error on python3.4:

_Traceback (most recent call last):
File "auth_sharepoint_online365.py", line 2, in
from office365.runtime.auth.authentication_context import AuthenticationContext
File "authentication_context.py", line 2, in
from office365.runtime.auth.saml_token_provider import SamlTokenProvider
File "saml_token_provider.py", line 2, in
import urlparse
ImportError: No module named 'urlparse'_

According to https://docs.python.org/2/library/urlparse.html:

The urlparse module is renamed to urllib.parse in Python 3.

Try this https://github.com/parthrawal/Python.O365 i have written .py file which can connect to the SharePoint Online and even has some methods to get the data from lists in dictionary format. Let me know if you need any help with it.

@vic-by A recent commit fixes the problem : https://github.com/vgrem/Office365-REST-Python-Client/commit/90731f
Note that at this time, this commit has not yet been pushed on pypi. So if you do a pip install Office365-REST-Python-Client you won't get that code. Installing from git will : pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

There is still work needed to get the library really with python 3.

I have encountered an encoding problem when running the library under python 3. It happened when doing a list.properties but I'm sure the problem is perpasive.

    ctx = ClientContext(url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    lists = web.lists
    ctx.load(lists)
    ctx.execute_query()
    lists[0].properties
 in <module>()
---> 16         lists[0].properties

c:\python\python35\lib\encodings\cp850.py in encode(self, input, final)
     17 class IncrementalEncoder(codecs.IncrementalEncoder):
     18     def encode(self, input, final=False):
---> 19         return codecs.charmap_encode(input,self.errors,encoding_map)[0]
     20
     21 class IncrementalDecoder(codecs.IncrementalDecoder):

UnicodeEncodeError: 'charmap' codec can't encode character '\u2019' in position 11052: character maps to <undefined>

I am having the same problem with Python 3: "ModuleNotFoundError: No module named 'urlparse'"
Testing the file SharePointOnline.py: Authentication Failure -> The entered and stored passwords do not match.

Did you try this link https://github.com/parthrawal/Python.O365 make sure you use the service account for the same

Yes. Copy / Paste the code, on the bottom:

if __name__ == "__main__":
    UserName = "[email protected]"
    # UserName = "[email protected]"
    Password = "my_password"
    TopLevelUrl = "https://company.sharepoint.com/"
    SPOnlineHeaders(UserName, Password, TopLevelUrl)

The following error is returned:

....
IndexError: list index out of range

To get more detail on the error, I've inserted, on SPOnlineHeaders, the following code (print(s)):

response = requests.post(url, data=SharepointOnlineAuth, headers=headers)
s = str(response.content)
print(s)

Response:
...wst:FailedAuthentication...The entered and stored passwords do not match...

I hope what you are using it is a service account

That is correct. I am using the service account.

Is password correct? can you please double check it. cause i tried running the code, it's working fine. But when i entered wrong password it throws "IndexError: list index out of range" error.

Yes. The password is correct. This is what's happening when doing a manually login.

I write the link into the browser: https://company.sharepoint.com/

When pressing enter I am redirected to the login page: https://login.microsoftonline.com/575...71a/oauth2/authorize?client_id=...&response_mode=form_post&response_type=code%20id_token&resource=...&scope=openid&nonce=....&redirect_uri=https:%2F%2Fcompany.sharepoint.com%2F_forms%2Fdefault.aspx&wsucxt=1&client-request-id=....

After pressing the ok button at the login page I saw two fast links...
First: https://sts.company.com/adfs/ls/wia?client-request-id=...&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=LoginOptions%3D3%26estsredirect%3d2%26estsrequest%....&cbcxt=&username=myemail%company.com&mkt=&lc=
... And ...
Second: https://login.microsoftonline.com/login.srf?client-request-id=...

And finally stops at the required page:
https://company.sharepoint.com/

I run this code found that it is throwing 403 error somewhere in code.

response = requests.post(url,data=SharepointOnlineAuth,headers=headers)
s = str(response.content)
print(s)
"b'403 FORBIDDEN'"

I forgot to use endpoint

url="https://login.microsoftonline.com/extSTS.srf"

urlpar

I'm having the same problem with urlparse (Python 3.6.5 :: Anaconda, Inc.). This was solved by modifying saml_token_provider.py: from urllib.parse import urlparse [...] url = urlparse(self.url)

Then I was missing web, which I installed it with: pip install lpthw.web. However, there seems to be an issue, as now I'm getting the following problem:
from web import Web File "C:\ProgramData\Anaconda3\lib\site-packages\web\__init__.py", line 14, in <module> import utils, db, net, wsgi, http, webapi, httpserver, debugerror ModuleNotFoundError: No module named 'utils'

Install the utils module in anaconda.

Install the utils module in anaconda.

Thanks. After installing utils, I also needed to install db...it might be useful to have a requirements.txt check in the package?

What is happening now is that the print statements are not adequate for python3:
print "var", var ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("var", var)?

Please go through following link:
https://docs.python.org/3.0/whatsnew/3.0.html

@viogp Thanks for posting your progress here, would be good if we can iron some of these kinks out. Currently are using this library in py 2.7 and would like to these workflows over to py 3.

Hi. I have a problem using this library.
An error occurred while retrieving token: AADSTS90023: Invalid STS request.
An error occurred while retrieving auth cookies
return 'FedAuth=' + self.FedAuth + '; rtFa=' + self.rtFa
TypeError: can only concatenate str (not "NoneType") to str
Any can help me?

Since the library is officially compatible with both Python 2 and Python 3 runtimes, propose to close this issue.

hi,

I am getting this error "ModuleNotFoundError: No module named 'office365.sharepoint.client_context'" when I use project environment in pycharm during running. BUT it will work just fine if i use Python system environment. The same behavior either I use Python 3.6 or 3.7.

Please help!
Thanks.

Was this page helpful?
0 / 5 - 0 ratings