Office365-rest-python-client: Как я могу загрузить файл на sharepoint?

Созданный на 14 июл. 2017  ·  10Комментарии  ·  Источник: vgrem/Office365-REST-Python-Client

Я пытаюсь загрузить файл на sharepoint, я на правильном пути?

def upload_file(ctx, listTitle, path):
    list_obj = ctx.web.lists.get_by_title(listTitle)
    folder = list_obj.root_folder
    ctx.load(folder)
    ctx.execute_query()

    files = folder.files
    with open(path, 'rb') as f:
        content = f.read()
        file_creation_information = FileCreationInformation()
        file_creation_information.overwrite = True
        file_creation_information.url = path
        file_creation_information.content = content
        file_new = files.add(file_creation_information)
question

Самый полезный комментарий

@benpolinsky Спасибо за публикацию фрагментов, в конце концов, у меня все заработало. Сначала у меня были проблемы с получением дайджеста формы, но как только я понял, как это сделать, это сработало.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.runtime.utilities.request_options import RequestOptions

from office365.sharepoint.file_creation_information import FileCreationInformation
from settings import settings
import requests
import os
from os.path import basename


ctx_auth = AuthenticationContext(url=settings['url'])
if ctx_auth.acquire_token_for_user(username=settings['username'], password=settings['password']):
    upload_binary_file("c:\temp\myfile.txt",ctx_auth)

def upload_binary_file(file_path, ctx_auth):
    """Attempt to upload a binary file to SharePoint"""

    base_url = settings['url']
    folder_url = "MyFolder"
    file_name = basename(file_path)
    files_url ="{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}', overwrite=true)"
    full_url = files_url.format(base_url, folder_url, file_name)

    options = RequestOptions(settings['url'])
    context = ClientContext(settings['url'], ctx_auth)
    context.request_form_digest()

    options.set_header('Accept', 'application/json; odata=verbose')
    options.set_header('Content-Type', 'application/octet-stream')
    options.set_header('Content-Length', str(os.path.getsize(file_path)))
    options.set_header('X-RequestDigest', context.contextWebInformation.form_digest_value)
    options.method = 'POST'

    with open(file_path, 'rb') as outfile:

        # instead of executing the query directly, we'll try to go around
        # and set the json data explicitly

        context.authenticate_request(options)

        data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)

        if data.status_code == 200:
            # our file has uploaded successfully
            # let's return the URL
            base_site = data.json()['d']['Properties']['__deferred']['uri'].split("/sites")[0]
            relative_url = data.json()['d']['ServerRelativeUrl'].replace(' ', '%20')

            return base_site + relative_url
        else:
            return data.json()['error']

Все 10 Комментарий

Я использовал только ClientRequest class для этого.

   def upload_binary_file(self, file):
        """Attempt to upload a binary file to SharePoint"""

        folder_url = "folder_to_upload_to"
        text_file = basename(file.name)
        full_url = "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}', overwrite=true)".format(self.base_url, folder_url, text_file)
        options = RequestOptions(full_url)
        context = ClientContext(full_url, self.ctx_auth)
        options.set_header('Accept', 'application/json; odata=verbose')
        options.set_header('Content-Type', 'application/octet-stream')
        options.set_header('Content-Length', str(os.path.getsize(file.name)))
        options.set_header('X-RequestDigest', YOUR_FORM_DIGEST)
        options.method = 'POST'
        file_name = file.name        
        with open(file_name, 'rb') as outfile:

            # instead of executing the query directly, we'll try to go around
            # and set the json data explicitly

            context.authenticate_request(options)

            data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)
            if data.status_code == 200:
                # our file has uploaded successfully
                # let's return the URL
                base_site = data.json()['d']['Properties']['__deferred']['uri'].split("/sites")[0]
                relative_url = data.json()['d']['ServerRelativeUrl'].replace(' ', '%20')

                return base_site + relative_url
            else:
                return "Log Failed to Upload" 

@benpolinsky Спасибо за публикацию фрагментов, в конце концов, у меня все заработало. Сначала у меня были проблемы с получением дайджеста формы, но как только я понял, как это сделать, это сработало.

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.runtime.utilities.request_options import RequestOptions

from office365.sharepoint.file_creation_information import FileCreationInformation
from settings import settings
import requests
import os
from os.path import basename


ctx_auth = AuthenticationContext(url=settings['url'])
if ctx_auth.acquire_token_for_user(username=settings['username'], password=settings['password']):
    upload_binary_file("c:\temp\myfile.txt",ctx_auth)

def upload_binary_file(file_path, ctx_auth):
    """Attempt to upload a binary file to SharePoint"""

    base_url = settings['url']
    folder_url = "MyFolder"
    file_name = basename(file_path)
    files_url ="{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}', overwrite=true)"
    full_url = files_url.format(base_url, folder_url, file_name)

    options = RequestOptions(settings['url'])
    context = ClientContext(settings['url'], ctx_auth)
    context.request_form_digest()

    options.set_header('Accept', 'application/json; odata=verbose')
    options.set_header('Content-Type', 'application/octet-stream')
    options.set_header('Content-Length', str(os.path.getsize(file_path)))
    options.set_header('X-RequestDigest', context.contextWebInformation.form_digest_value)
    options.method = 'POST'

    with open(file_path, 'rb') as outfile:

        # instead of executing the query directly, we'll try to go around
        # and set the json data explicitly

        context.authenticate_request(options)

        data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)

        if data.status_code == 200:
            # our file has uploaded successfully
            # let's return the URL
            base_site = data.json()['d']['Properties']['__deferred']['uri'].split("/sites")[0]
            relative_url = data.json()['d']['ServerRelativeUrl'].replace(' ', '%20')

            return base_site + relative_url
        else:
            return data.json()['error']

Я бы предпочел иметь простой API для загрузки файла в sharepoint. Это слишком сложно.

@attibalazs Спасибо за сценарий. Я столкнулся со следующей ошибкой и сейчас застрял здесь:

Файл "C: \ Python27 \ lib \ site-packages \ office365 \ runtime \ auth \ saml_token_provider.py", строка 65, в get_authentication_cookie
return 'FedAuth =' + self.FedAuth + '; rtFa = '+ self.rtFa
TypeError: невозможно объединить объекты 'str' и 'NoneType'

Вам также нужно было использовать идентификатор клиента и секрет клиента в дополнение к URL-адресу SP Online, имени пользователя и паролю?

Спасибо за это @attibalazs . У меня это сработало.

Я сомневаюсь .. Работает ли этот код для учетных записей организаций, таких как office365, например

Привет, я использовал сценарий @attibalazs , который, кажется, работает хорошо, пока я не попытаюсь загрузить данные в Sharepoint:
data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)

Получил статус 403. Есть ли что-то, что я должен изменить в конфигурации моей офисной учетной записи, чтобы получить права на запись в Sharepoint таким образом?

@attibalazs
использовать API. status = ctx_auth.acquire_token_for_app () вместо status = ctx_auth.acquire_token_for_user (имя пользователя, пароль)
и установите packge. pip install -U certifi

Здравствуйте, я добавил несколько исправлений в ваш код, которые у меня работают:

Я пытаюсь загрузить файл на sharepoint, я на правильном пути?

``
def upload_file (ctx, listTitle, путь):
list_obj = ctx.web.lists.get_by_title (listTitle)
folder = list_obj.root_folder
ctx.load (папка)
ctx.execute_query ()

files = folder.files
    ctx.load(files)
    ctx.execute_query()
with open(path, 'rb') as f:
    content = f.read()
    file_creation_information = FileCreationInformation()
    file_creation_information.overwrite = True
       file_creation_information.url = os.path.basename(path)
    file_creation_information.content = content
    file_new = files.add(file_creation_information)
       ctx.load(files)
       ctx.execute_query()

Привет,

Предлагаю закрыть этот вопрос, поскольку на него был дан ответ.

Обобщить:

Рекомендуемый способ загрузки файла в библиотеку SharePoint показан ниже:

#read a local file
path = "../tests/data/SharePoint User Guide.docx"
with open(path, 'rb') as content_file:
    file_content = content_file.read()

#upload it into Documents library
target_folder = context.web.lists.get_by_title("Documents").rootFolder
info = FileCreationInformation()
info.content = file_content
info.url = os.path.basename(path)
info.overwrite = True
target_file = target_folder.files.add(info)
context.execute_query()

Но если размер файла превышает 2 МБ, файл необходимо загрузить в виде набора кусков:

ctx = ClientContext(site_url, ctx_auth)
size_1Mb = 1000000
local_path = "./data/big_buck_bunny.mp4"
target_url = "/Shared Documents"
result_file = ctx.web.get_folder_by_server_relative_url(target_url).files.create_upload_session(local_path, size_1Mb, print_upload_progress)
ctx.execute_query()
print('File {0} has been uploaded successfully'.format(result_file.properties['ServerRelativeUrl']))

где

def print_upload_progress(offset):
    print("Uploaded '{0}' bytes...".format(offset))

Если вы предпочитаете создавать запрос на загрузку самостоятельно, вам подойдут фрагменты, предоставленные @attibalazs и @benpolinsky .

Вадим

Была ли эта страница полезной?
0 / 5 - 0 рейтинги