Forum Discussion

metatrons's avatar
metatrons
Copper Contributor
Jun 05, 2020

I want to upload file to Sharepoint via python.

I faced a problem.

Response<403>
'X-MSDAVEXT_Error': '917656; Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically.'

Here is my code.

 

```

import requests
from shareplum import Office365
from config_s import config_s
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

# get data from configuration
username = config_s['sp_user']
password = config_s['sp_password']
site_name = config_s['sp_site_name']
base_path = config_s['sp_base_path']
doc_library = config_s['sp_doc_library']

url_me = "https://vpon365.sharepoint.com/sites/msteams_ffbb68/"
client_id = config_s['client_id']
client_secret = config_s['client_secret']


file_name = "test.csv"
# Obtain auth cookie
authcookie = Office365(base_path, username=username, password=password).GetCookies()
session = requests.Session()
session.cookies = authcookie
session.headers.update({'user-agent': 'python_bite/v1'})
session.headers.update({'accept': 'application/json;odata=verbose'})

# ctx_auth = AuthenticationContext(url_me)
# if ctx_auth.acquire_token_for_app(client_id, client_secret):
# ctx = ClientContext(url_me, ctx_auth)
# web = ctx.web
# ctx.load(web)
# ctx.execute_query()
# print ("Web title: {0}".format(web.properties['Title']))

# dirty workaround.... I'm getting the X-RequestDigest from the first failed call
session.headers.update({'X-RequestDigest': 'FormDigestValue'})
response = session.post( url=base_path + "/sites/" + site_name +
"/_api/web/GetFolderByServerRelativeUrl('" + doc_library +
"')/Files/add(url='a.txt',overwrite=true)",
data="")
session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})
print(response)
print(response.headers)

# perform the actual upload

with open( r'/Users/Metatrons/Desktop/AutoReport_Structure/test.csv', 'rb+') as file_input:
try:
response = session.post(
url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='"
+ file_name + "',overwrite=true)",
data=file_input)
print(response)
print(response.headers)
print()
except Exception as err:
print("Some error occurred: " + str(err))

print('end...')

```

 

Plz help me to solve this problem, thank you sincerely.

No RepliesBe the first to reply

Resources