3

Similar to this question I'm having trouble opening a file uploaded via Python onto SharePoint. This is the code I'm using to upload the file:

import requests
from requests_ntlm import HttpNtlmAuth

session = requests.Session()
session.auth = HttpNtlmAuth('DOMAIN\\username','password', session)

files = {'file': ('_test.xlsx', open('_test.xlsx','rb'),
         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
         {'Expires': '0'})
        }

put_url = 'https://secure.sp.kp.org/teams/scpmgcc/complete%20care/Proactive%20Care/POE_CCTE_TAT/2017%20Reports'
myFile = requests.put('{}/_test.xlsx'.format(put_url), 
                      files=files, 
                      auth=session.auth)

The error message is below:

enter image description here

Is SharePoint doing anything to the upload? Should I be encoding the data somehow? Thank you for any assistance you can provide.

1
  • I cannot make a comment, so I ask about the answer here! The answer which is marked as solution does not work for me. It does not give me any error, but no file is uploaded to the website! What should I do? btw, what does the "header" do?
    – mah65
    Commented Nov 12, 2019 at 0:26

2 Answers 2

4

Figured out the problem with my original code:
needed to provide data kwarg and NOT files kwarg:

import requests
from requests_ntlm import HttpNtlmAuth
session = requests.Session()
session.auth = HttpNtlmAuth('DOMAIN\\username','password', session)

put_url = 'https://secure.sp.kp.org/teams/scpmgcc/complete%20care/Proactive%20Care/POE_CCTE_TAT/2017%20Reports'
with open('p:/ccte/_ccte_tat_template.xls','rb') as fin:
    myFile = requests.put('{}/_ccte_tat_template.xls'.format(put_url), 
                          data=fin.read(), 
                          auth=session.auth, 
                          headers={'content-type':'application/vnd.ms-excel'})
1

I was able to work around this using urllib2:

import os, urllib2

from ntlm import HTTPNtlmAuthHandler

base_url = "https://secure.sp.kp.org"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, base_url, 'DOMAIN\\username', 'password')
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)
filepath = 'p:/ccte/_ccte_tat_template.xls'
dirname, filename = os.path.split(filepath)
put_url = '{}/teams/scpmgcc/complete%20care/Proactive%20Care/POE_CCTE_TAT/2017%20Reports/{}'.format(base_url,filename)
with open(filepath,'rb') as fin:
  request = urllib2.Request(put_url,data=fin.read())

request.get_method = lambda: 'PUT'
url = opener.open(request)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.