コード例 #1
0
 def setUpClass(cls):
     ctx_auth = AuthenticationContext(url=settings['url'])
     ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'],
                                     password=settings['user_credentials']['password'])
     cls.context = ClientContext(settings['url'], ctx_auth)
コード例 #2
0
    def post_entities(entities: list):

        ctx_auth = AuthenticationContext(URL)

        ctx_auth.acquire_token_for_user(USERNAME, PASSWORD)
        if ctx_auth.provider.token:
            ctx = ClientContext(URL, ctx_auth)
        else:
            error = ctx_auth.get_last_error()
            logging.error(error)
            raise Exception(error)

        for _, entity in enumerate(entities):
            if entity['_deleted'] and not PROCESS_DELETED:
                logging.debug(
                    f"entity {entity['_id']} marked as deleted and will not be processed"
                )
                continue

            list_object = ctx.web.lists.get_by_title(entity[LIST_NAME])

            try:
                list_item_name = entity.get(LIST_ITEM_NAME)
                if list_item_name is None:
                    item_properties_metadata = {}
                else:
                    item_properties_metadata = {
                        '__metadata': {
                            'type': list_item_name
                        }
                    }
                keys_to_send = entity['Keys']
                values_to_send = {
                    key: str(entity[key])
                    for key in keys_to_send
                }
                item_properties = {
                    **item_properties_metadata,
                    **values_to_send
                }

                existing_item = None
                if entity.get('ID'):
                    try:
                        existing_item = list_object.get_item_by_id(
                            entity.get('ID'))
                        ctx.load(existing_item)
                        ctx.execute_query()
                    except Exception as ie:
                        logging.warning(
                            "Item lookup by ID resulted in an exception from Office 365 {}"
                            .format(ie))
                        if (
                                hasattr(ie, 'code') and ie.code
                                == "-2147024809, System.ArgumentException"
                        ) or (hasattr(ie, 'message') and ie.message ==
                              "Item does not exist. It may have been deleted by another user."
                              ):
                            existing_item = None
                        else:
                            raise Exception from ie

                if not existing_item:
                    logging.info("Creating new item")
                    list_object.add_item(item_properties)
                    ctx.execute_query()
                else:
                    logging.info("Existing item found")
                    if entity.get('SHOULD_DELETE') is not None and bool(
                            entity.get('SHOULD_DELETE')):
                        response = delete_list_item(ctx, entity[LIST_NAME],
                                                    entity.get('ID'))
                    else:
                        response = update_list_item(ctx, entity[LIST_NAME],
                                                    entity.get('ID'),
                                                    values_to_send)
                    response.raise_for_status()

            except Exception as e:
                error_message = f"An exception occurred during processing of an entity: {e} ({json.dumps(entity)}"
                logging.error(error_message)
                raise Exception(error_message) from e
コード例 #3
0
        print("Item title: {0}".format(item.properties["Title"]))


def create_list_item():
    print("Create list item example...")
    list_object = ctx.web.lists.get_by_title(listTitle)
    item_properties = {
        '__metadata': {
            'type': 'SP.Data.TasksListItem'
        },
        'Title': 'New Task'
    }
    item = list_object.add_item(item_properties)
    ctx.execute_query()
    print("List item '{0}' has been created.".format(item.properties["Title"]))


if __name__ == '__main__':
    ctxAuth = AuthenticationContext(url=settings['url'])
    if ctxAuth.acquire_token_for_user(
            username=settings['user_credentials']['username'],
            password=settings['user_credentials']['password']):
        ctx = ClientContext(settings['url'], ctxAuth)

        # read_list_items()
        # create_list_item()
        filter_list_items()

    else:
        print(ctxAuth.get_last_error())
コード例 #4
0
from office365.runtime.client_request import ClientRequest
from office365.sharepoint.files.file import File

# Import Authentication tokens
from decouple import config
""" Sharepoint File Access """

sharepoint_url = config('sharepoint')
username = config('username')  #input('username: '******'password')  #getpass.getpass()
site_url = config('site')
folder_url = config('folder')

# Access sharepoint folder with authentication
ctx_auth = AuthenticationContext(sharepoint_url)
if ctx_auth.acquire_token_for_user(username, password):
    request = ClientRequest(ctx_auth)
    ctx = ClientContext(site_url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    print(f"\n...Logged into: {web.properties['Title']}...")

else:
    print(ctx_auth.get_last_error())


# Function to load a file from sharepoint onto python
def load_file(filename):
    # Open the file in temporary memory
    response = File.open_binary(ctx, str(folder_url + filename))
コード例 #5
0
ファイル: BatteryDocs.py プロジェクト: ZWillChen/djTEST
def AuthenticateSharepoint(sharepoint_url, user, password):
    ctx_auth = AuthenticationContext(sharepoint_url)
    ctx_auth.acquire_token_for_user(user, password)
    ctx = ClientContext(sharepoint_url, ctx_auth)
    return ctx
コード例 #6
0
        print("Task '{0}' has been created".format(
            task_item.properties["Title"]))


def generate_contacts(context):
    contacts_list = ctx.web.lists.get_by_title("Contacts")
    fake = Faker()
    for idx in range(0, 1):
        name = fake.name()
        contact_properties = {
            '__metadata': {
                'type': 'SP.Data.ContactsListItem'
            },
            'Title': name
        }
        contact_item = contacts_list.add_item(contact_properties)
        context.execute_query()
        print("Contact '{0}' has been created".format(
            contact_item.properties["Title"]))


if __name__ == '__main__':
    ctx_auth = AuthenticationContext(url=settings['url'])
    if ctx_auth.acquire_token_for_user(username=settings['username'],
                                       password=settings['password']):
        ctx = ClientContext(settings['url'], ctx_auth)
        generate_tasks(ctx)
        # generate_contacts(ctx)
    else:
        print(ctx_auth.get_last_error())
コード例 #7
0
        self.tokenServer = tokenServer
        self.url = url
        self.site = site


confObject = sConf(ci_tokenServer, site_url, site_site)

# from sharepoint.SharePointClientUtil import SharePoint_Client_Util

# sharepointClient = SharePoint_Client_Util.create_sharepoint_client(confObject, site_username, site_password)
# FormDigestValue = sharepointClient.get_digest()
#     we are going to manually get the digest

# Some more setup
ctx_auth = AuthenticationContext(ci_tokenServer, site_url)
ctx_auth.acquire_token_for_user(site_username, site_password)
request = ClientRequest(ctx_auth)

options = RequestOptions(site_url + "/Sites/" + site_site +
                         "/_api/contextinfo")
options.method = 'POST'
options.set_header('Accept', 'application/json')
options.set_header('Content-Type', 'application/json')
data = request.execute_request_direct(options)
digest = json.loads(data.content)['FormDigestValue']

# If the script has reached this point, our session is authenticated
# Run payload (your desired action) here

# Move/Rename
# options = RequestOptions("{0}/_api/web/GetFileByServerRelativeUrl('" + sourcePath + "')/moveto(newurl='" + destinationPath + "',flags=1)".format(site_url))
コード例 #8
0
import json

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_request import ClientRequest
from office365.runtime.utilities.request_options import RequestOptions

tenant_url = "https://{tenant}.sharepoint.com"
ctx_auth = AuthenticationContext(tenant_url)

site_url = "https://{tenant}.sharepoint.com/sites/{yoursite}"

if ctx_auth.acquire_token_for_user("username", "password"):
    request = ClientRequest(ctx_auth)
    options = RequestOptions("{0}/_api/web/".format(site_url))
    options.set_header('Accept', 'application/json')
    options.set_header('Content-Type', 'application/json')
    data = request.execute_request_direct(options)
    s = json.loads(data.content)
    web_title = s['Title']
    print("Web title: " + web_title)
else:
    print(ctx_auth.get_last_error())
コード例 #9
0
ファイル: tosharepoint.py プロジェクト: Eliot-M/SlackBotSvg
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
import pandas as pd
url = 'https://s.'

ctx_auth = AuthenticationContext(url)
ctx_auth.acquire_token_for_user('e.com', 'xxx')
ctx = ClientContext(url, ctx_auth)
response = File.open_binary(ctx, "/veille.csv")
with open("./veille.csv", "wb") as local_file:
    local_file.write(response.content)


コード例 #10
0
ファイル: sharepoint.py プロジェクト: tomkcook/obsync
class SharePoint():
    def __init__(self, url, username, password):
        self.site_url = url
        if self.site_url[-1] != '/':
            self.site_url += '/'
        self.username = username
        self.password = password
        self.connected = False

    def connect(self):
        self.ctx_auth = AuthenticationContext(self.site_url)
        self.connected = self.ctx_auth.acquire_token_for_user(
            self.username, self.password)
        self.request = ClientRequest(self.ctx_auth)
        print('Authentication was {}successful'.format(
            'not ' if not self.connected else ''))
        return self.connected

    @authenticate
    def get(self, path):
        #        request = ClientRequest(self.ctx_auth)
        options = RequestOptions('{}_api/web/{}'.format(self.site_url, path))
        options.set_header('Accept', 'application/json')
        options.set_header('Content-Type', 'application/json')
        data = self.request.execute_request_direct(options)
        if data.status_code == 404:
            raise ValueError('Site does not exist')
        s = json.loads(data.content)
        return s

    @authenticate
    def get_raw(self, path):
        #        request = ClientRequest(self.ctx_auth)
        options = RequestOptions('{}_api/web/{}'.format(self.site_url, path))
        data = self.request.execute_request_direct(options)
        return data

    @authenticate
    def post_raw(self, path, headers={}, data={}):
        options = RequestOptions('{}{}'.format(self.site_url, path))
        options.method = HttpMethod.Post
        options.set_headers(headers)
        if isinstance(data, abc.Mapping):
            options.data.update(data)
        data = self.request.execute_request_direct(options)
        if data.status_code == 403:
            import traceback
            traceback.print_tb()
            print(options.url)
            print(data.content)
            print(options.headers)
        return data

    @authenticate
    def post(self, path, headers={}, data={}):
        #        request = ClientRequest(self.ctx_auth)
        options = RequestOptions('{}_api/web/{}'.format(self.site_url, path))
        options.method = HttpMethod.Post
        options.set_headers(headers)
        options.data = data
        data = self.request.execute_request_direct(options)
        if data.status_code == 403:
            import traceback
            traceback.print_tb()
            print(options.url)
            print(data.content)
            print(options.headers)
        return data

    def get_digest(self):
        data = self.post_raw(
            '_api/contextinfo',
            headers=dict(Accept='application/json; odata=verbose'))
        data = json.loads(data.content)
        return data['d']['GetContextWebInformation']['FormDigestValue']

    def lists(self):
        return self.get('lists')

    def get_list(self, name):
        return self.get("lists/getbytitle('{}')".format(quote_file(name)))

    def get_list_items(self, name):
        return self.get("lists/getbytitle('{}')/Items".format(
            quote_file(name)))

    def get_folder(self, path):
        return Folder(self, path, None)

    def get_file(self, path):
        return File(self, path)

    def find_file(self, root, path):
        file = self.get_folder(root)
        for x in path.components:
            file = file[x]
        return file

    def delete(self, path, is_folder=False):
        form_digest = self.get_digest()
        return self.post("Get{}ByServerRelativeUrl('{}')".format(
            'Folder' if is_folder else 'File', quote_file(path)),
                         headers={
                             'X-RequestDigest': form_digest,
                             'IF-MATCH': 'etag or "*"',
                             'X-HTTP-Method': 'DELETE'
                         })

    def create_file(self, path, f, size):
        form_digest = self.get_digest()
        return self.post(
            "GetFolderByServerRelativeUrl('{}')/Files/add(url='{}', overwrite=true)"
            .format(quote_file(path.parent), quote_file(path.name)),
            headers={
                'X-RequestDigest': form_digest,
                'Content-Length': str(size)
            },
            data=f)

    def create_folder(self, path):
        form_digest = self.get_digest()
        return self.post("folders",
                         headers={
                             'X-RequestDigest': form_digest,
                             'accept': 'application/json;odata=verbose',
                             'content-type': 'application/json;odata=verbose'
                         },
                         data={
                             '__metadata': {
                                 'type': 'SP.Folder'
                             },
                             'ServerRelativeUrl': str(path)
                         })