def eventFromSharePoint(): collection = db['calendar'] calendar_url = "https://mirageworks.sharepoint.com/sites/msteams_a0f4c8/_api/web/lists(guid'%s')/items" %(ACCOUNT['guid']) ctx = ClientContext(calendar_url).with_credentials(UserCredential(ACCOUNT['email'], ACCOUNT['password'])) request = RequestOptions(calendar_url) response = ctx.execute_request_direct(request) json_data = json.loads(response.content) for i, data in enumerate(json_data['d']['results']): event = {} event['title'] = data['Title'] event['start'] = data['EventDate'] event['end'] = data['EndDate'] event['id'] = data['ID'] event['allday'] = data['fAllDayEvent'] event['every'] = data['fRecurrence'] if data['fRecurrence']: collection.update_one({'id': event['id']}, {'$set': event}, upsert=True) else: collection.update_one({'id': event['id']}, {'$set': event}, upsert=True)
import json from settings import settings from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.http.request_options import RequestOptions from office365.sharepoint.client_context import ClientContext if __name__ == '__main__': context_auth = AuthenticationContext(url=settings['url']) if context_auth.acquire_token_for_user( username=settings['user_credentials']['username'], password=settings['user_credentials']['password']): """Read Web client object""" ctx = ClientContext(settings['url'], context_auth) options = RequestOptions("{0}/_api/web/".format(settings['url'])) options.set_header('Accept', 'application/json') options.set_header('Content-Type', 'application/json') data = ctx.execute_request_direct(options) json = json.loads(data.content) web_title = json['Title'] print("Web title: {0}".format(web_title)) else: print(context_auth.get_last_error())
import json from office365.runtime.http.request_options import RequestOptions from office365.sharepoint.client_context import ClientContext from tests import test_user_credentials, test_site_url if __name__ == '__main__': """Demonstrates how to construct and submit requests without model involved""" ctx = ClientContext(test_site_url).with_credentials(test_user_credentials) request = RequestOptions("{0}/_api/web/".format(test_site_url)) response = ctx.execute_request_direct(request) json = json.loads(response.content) web_title = json['d']['Title'] print("Web title: {0}".format(web_title))
class SharepointUpload(Downloader): def __init__(self, settings_path): super().__init__(__version__, r"/home/downloader_settings", settings_path) context_auth = AuthenticationContext(url=site_url) context_auth.acquire_token_for_app( client_id=app_principal['client_id'], client_secret=app_principal['client_secret']) self.ctx = ClientContext(site_url, context_auth) @retry(Exception, 4, delay=60, backoff=2) def upload_file_to_sp(self, file_path, *remote_path): folder_url = "/".join(["Shared Documents", "beta_builds"] + list(remote_path)) target_folder = self.ctx.web.ensure_folder_path(folder_url) size_chunk = 100 * 1024 * 1024 # MB file_size = os.path.getsize(file_path) if file_size > size_chunk: result_file = target_folder.files.create_upload_session( file_path, size_chunk, self.print_upload_progress, file_size) else: with open(file_path, 'rb') as content_file: file_content = content_file.read() name = os.path.basename(file_path) result_file = target_folder.upload_file(name, file_content) self.ctx.execute_query() request = RequestOptions( r"{0}web/getFileByServerRelativeUrl('{1}')/\$value".format( self.ctx.service_root_url(), result_file.serverRelativeUrl)) request.stream = True response = self.ctx.execute_request_direct(request) remote_size = int(response.headers['Content-Length']) if abs(file_size - remote_size) > 0.05 * file_size: raise UploaderError("File size difference is more than 5%") logging.info('File {0} has been uploaded successfully'.format( result_file.serverRelativeUrl)) return folder_url @retry(Exception, 4) def add_list_item(self, file_url, build_date, folder_url): product_list = self.ctx.web.lists.get_by_title("product_list") product_list.add_item({ "Title": self.settings.version, "build_date": build_date, "relative_url": file_url, "shareable_folder": f"{site_url}/{folder_url}" }) self.ctx.execute_query() @retry(Exception, 4) def get_list_items(self): product_list = self.ctx.web.lists.get_by_title("product_list") items = product_list.items self.ctx.load(items) self.ctx.execute_query() return items @staticmethod def print_upload_progress(offset, total_size): logging.info("Uploaded '{}' MB from '{}'...[{}%]".format( round(offset / 1024 / 1024, 2), round(total_size / 1024 / 1024, 0), round(offset / total_size * 100, 2)))
import json from office365.sharepoint.client_context import ClientContext from tests import test_user_credentials, test_site_url if __name__ == '__main__': """Demonstrates how to construct and submit requests without model involved""" client = ClientContext(test_site_url).with_credentials( test_user_credentials) response = client.execute_request_direct("web") response.raise_for_status() json = json.loads(response.content) web_title = json['d']['Title'] print("Web title: {0}".format(web_title))
class APIPoint: __timeStamp = " " __ctx = None __site_url = None __count = 0 def login(self): try: self.__site_url = StringUtils.StringUtils.websiteAPI self.__ctx = ClientContext(self.__site_url).with_credentials( UserCredential(StringUtils.StringUtils.email, StringUtils.StringUtils.passwort)) except ValueError: raise LoginException def getWebTitle(self): request = RequestOptions("{0}/_api/files".format(self.__site_url)) response = self.__ctx.execute_request_direct(request) js = json.loads(response.content) web_title = js['d']['results'] return web_title def iterateJSON(self): web_title = self.getWebTitle() for i in web_title: for attribute, value in i.items(): if attribute == 'TimeLastModified': if self.__timeStamp < value: self.__timeStamp = value for k, v in islice(i.items(), 1, None): if k == 'Name': fileName = str(v) if fileName.lower().endswith('.doc') or fileName.lower().endswith('.docx'): print("Eine Word-Datei wurde geändert !") print("Datei: " + fileName + " wurde geändert !\n") def countFiles(self): count2 = 0 web_title = self.getWebTitle() for i in web_title: count2 += 1 if self.__count < count2: print("Neue Datei hinzugekommen !!") self.__count = count2 break return self.__count def init(self): print("Start init:") web_title = self.getWebTitle() for i in web_title: self.__count += 1 for attribute, value in i.items(): if attribute == 'TimeLastModified': if self.__timeStamp < value: self.__timeStamp = value print("Anzahl an Dateien:", self.__count)