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']) ctx_auth.acquire_token_for_app(client_id=settings['client_credentials']['client_id'], client_secret=settings['client_credentials']['client_secret']) cls.context = ClientContext(settings['url'], ctx_auth)
def __upload_target_reports(adm_sp_value: ADMSharepointValue) -> None: site_url = adm_sp_value.sharepoint_value.site_url + 'sites/' + adm_sp_value.sharepoint_value.site_id context_auth = AuthenticationContext(url=site_url) context_auth.acquire_token_for_app( client_id=adm_sp_value.sharepoint_value.client_id, client_secret=adm_sp_value.sharepoint_value.client_secret) ctx = ClientContext(site_url, context_auth) target_report_values = adm_sp_value.target_report_values # Create folder structure new_path = __create_folder(ctx, adm_sp_value) # Upload reports without segment by configuration if target_report_values is not None: for target_report_value in target_report_values: file_path = target_report_value.target_report_location if file_path is not None: files = glob.glob(file_path) __upload_file(files, new_path, ctx) # Upload reports with segment by configuration target_report_segment_values = target_report_value.target_report_segment_values if target_report_segment_values is not None: for target_report_segment_value in target_report_segment_values: segment_by_value = target_report_segment_value.target_report_segment_by_field_value segment_file_path = target_report_segment_value.target_report_segment_report_location segment_files = glob.glob(segment_file_path) __upload_file(segment_files, new_path, ctx, segment_by_value)
def alterarGeradas(ID, sumGeradas): # Definindo parametros de conexão # ID e Senha criados pelo portal do sharepoint app_settings = { 'url': 'https://usinacoruripe.sharepoint.com/sites/FaturamentoTorta', 'client_id': 'c74022f1-d1b5-47e3-913f-84d7a98cf032', 'client_secret': 'qfHtOWl6YieOhGAAavzuzUDvuf9pl2ZvD/0JSqvZhsQ=' } # Chamando conexão com API Rest context_auth = AuthenticationContext(url=app_settings['url']) context_auth.acquire_token_for_app( client_id=app_settings['client_id'], client_secret=app_settings['client_secret']) ctx = ClientContext(app_settings['url'], context_auth) # Puxando valores da lista listaShare = ctx.web.lists.get_by_title("Autorizações") items = listaShare.get_items() ctx.load(items) ctx.execute_query() item = listaShare.get_item_by_id(ID) item.set_property('OData__x006d_kv6', sumGeradas) item.update() ctx.execute_query()
def test2_connect_with_app_principal_alt(self): context_auth = AuthenticationContext(url=test_site_url) context_auth.acquire_token_for_app( client_id=settings.get('client_credentials', 'client_id'), client_secret=settings.get('client_credentials', 'client_secret')) ctx = ClientContext(test_site_url, context_auth) self.assertIsInstance(ctx.authentication_context._provider, ACSTokenProvider)
def connect_with_credentials(cls, base_url, credentials): ctx_auth = AuthenticationContext(url=base_url) if isinstance(credentials, ClientCredential): ctx_auth.acquire_token_for_app(client_id=credentials.clientId, client_secret=credentials.clientSecret) elif isinstance(credentials, UserCredential): ctx_auth.acquire_token_for_user(username=credentials.userName, password=credentials.password) else: raise ValueError("Unknown credential type") return cls(base_url, ctx_auth)
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)
import requests from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext context_auth = AuthenticationContext( url='https://share-intra.philips.com/sites/STS020161021115113') context_auth.acquire_token_for_app( client_id='a6a115ee-fe4b-401d-b706-fbeb557f8669', client_secret='GKlYLuxQTDOrrBsDwE2a3TQ9IJihKL9Yr2r5J/ZPSbw=') # session = requests.Session() # session.cookies ctx = ClientContext('https://share-intra.philips.com/sites/STS020161021115113', context_auth) folder_url = "Shared%20Documents" #folder url where to find folder_name = "ADM" #folder name to find result = ctx.web.get_folder_by_server_relative_url(folder_url).folders.filter( "Name eq '{0}'".format(folder_name)) ctx.load(result) ctx.execute_query() if len(result) > 0: print("Folder has been found: {0}".format(result[0].properties["Name"]))
if result is None: result = [] ctx = parent_web.context webs = parent_web.webs ctx.load(webs) ctx.execute_query() result = result + list(webs) for web in webs: result = get_all_webs(web, result) return result if __name__ == '__main__': ctxAuth = AuthenticationContext(url=settings['url']) if ctxAuth.acquire_token_for_app( client_id=settings['client_credentials']['client_id'], client_secret=settings['client_credentials']['client_secret']): ctx = ClientContext(settings['url'], ctxAuth) # web = load_web(ctx) # web = create_web(ctx) # update_web(web) # delete_web(web) #root_web = ctx.web #ctx.load(root_web) #ctx.execute_query() #print_webs_recursively(root_web) all_webs = get_all_webs(ctx.web) for w in all_webs: print(w.properties['Url']) #print_webs_recursively(all_webs) else:
def setUpClass(cls): ctx_auth = AuthenticationContext(url=cls.site_url) ctx_auth.acquire_token_for_app(client_id=cls.client_id, client_secret=cls.client_secret) cls.client = ClientContext(settings['url'], ctx_auth)
from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.client_request import ClientRequest from office365.runtime.utilities.request_options import RequestOptions from office365.sharepoint.client_context import ClientContext app_settings = { 'url': 'https://contoso.sharepoint.com/', 'client_id': '8efc226b-ba3b-4def-a195-4acdb8d20ca9', 'client_secret': '', } if __name__ == '__main__': context_auth = AuthenticationContext(url=app_settings['url']) if context_auth.acquire_token_for_app( client_id=app_settings['client_id'], client_secret=app_settings['client_secret']): """Read Web client object""" ctx = ClientContext(app_settings['url'], context_auth) request = ClientRequest(ctx) options = RequestOptions("{0}/_api/web/".format(app_settings['url'])) options.set_header('Accept', 'application/json') options.set_header('Content-Type', 'application/json') data = ctx.execute_request_direct(options) s = json.loads(data.content) web_title = s['Title'] print("Web title: {0}".format(web_title)) else: print(context_auth.get_last_error())
from office365.runtime.auth.authentication_context import AuthenticationContext from office365.sharepoint.client_context import ClientContext from office365.runtime.client_request import ClientRequest from office365.runtime.utilities.request_options import RequestOptions from config import config import json username = config['sp_user'] password = config['sp_password'] url = config['sp_base_path'] client_id = config['sp_client_id'] client_secret = config['sp_client_secret'] ctx_auth = AuthenticationContext(url) if ctx_auth.acquire_token_for_app(client_id, client_secret): request = ClientRequest(ctx_auth) options = RequestOptions( "{0}/_api/web/lists/GetByTitle('Area')/items".format(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) print(s) else: print(ctx_auth.get_last_error())
class Sharepoint: """ Class that handles access to Sharepoint. """ _LOGIN_URL = "https://login.microsoftonline.com" _SCOPE = ".default" _MESSAGE = 2 # ClientRequestException.args[2] is error message def __init__(self, fconf, spconfig, runtime, logger): self._fconfig = fconf self._spconfig = spconfig self._runtime = runtime self._logger = logger self._context_auth = None self._url = None def __repr__(self): return str(self.__class__) + ": " + str(self.__dict__) def get_token(self): """ Acquire token for the site given the app client credentials. """ ## Use MSAL: # authority_url = self._LOGIN_URL + f"/{self._tenant_id}" # app = msal.ConfidentialClientApplication( # authority=authority_url, # client_id=self._client_id, # client_credential=self._client_secret, # validate_authority=False, # ) # token = app.acquire_token_for_client( # scopes=[self._client_id + f"/{self._SCOPE}"] # ) # if self._runtime.debug: # self._logger.debug(token) # return token if self._spconfig.subsite: self._url = self._spconfig.site + "/" + self._spconfig.subsite else: self._url = self._spconfig.site if self._runtime.debug: self._logger.debug(self._url) self._context_auth = AuthenticationContext(url=self._url) self._context_auth.acquire_token_for_app( client_id=self._spconfig.client, client_secret=self._spconfig.secret) def verify_url(self): """ Verify that the url given with runtime configuration actually exists on the Sharepoint site given in global configuration. Must authenticate using get_token first. """ ctx = ClientContext(self._url, self._context_auth) try: web = ctx.web.get().execute_query() except ClientRequestException as err: self._logger.error(err.args[self._MESSAGE]) return False self._logger.success(f"Site {web.properties['Title']}: {web.url}") return True def add_folder(self): """ Add folder given in FilesConfig.out to the list collection of the Sharepoint site from the configuration. """ ctx = ClientContext(self._url, self._context_auth) target_folder = ctx.web.lists.get_by_title("Documents").root_folder new_folder = target_folder.add(self._fconfig.out_folder) try: ctx.execute_query() except ClientRequestException as err: self._logger.error(err.args[self._MESSAGE]) return False self._logger.success(f"Added folder: {new_folder.serverRelativeUrl}") return True def upload_files(self): """ Upload files from configuration to the Sharepoint site from the configuration. """ ctx = ClientContext(self._url, self._context_auth) root = ctx.web.lists.get_by_title("Documents").root_folder target_folder = root.folders.get_by_url(self._fconfig.out_folder) file_size = 0 for f in self._fconfig.files: self._logger.info(f"File upload: {os.path.basename(f)}") file_size = os.path.getsize(f) with tqdm( total=file_size, file=sys.stdout, unit="B", unit_scale=True, unit_divisor=1024, ascii=True, ) as pbar: def display_upload_progress(offset): # pylint: disable=unused-argument # print_progress callback in create_upload_session requires # the offset parameter to show progress like: # (`offset` out of `file_size` uploaded) # but tqdm instead works with `chunk_size`, i.e. size of step to # update the progress bar. """ Callback used to print progress to stdout during file update. """ # pbar is only ever used here, so it's safe to silence # the warning from pylint. pbar.update( # pylint: disable=cell-var-from-loop self._runtime.chunk_size) uploaded_file = target_folder.files.create_upload_session( f, self._runtime.chunk_size, display_upload_progress) try: ctx.execute_query() except ClientRequestException as err: self._logger.error(err.args[self._MESSAGE]) return False self._logger.success( f"File {f} uploaded to: {uploaded_file.serverRelativeUrl}") return True
def conn(numero_autorizacao): # Definindo parametros de conexão # ID e Senha criados pelo portal do sharepoint app_settings = { 'url': 'https://usinacoruripe.sharepoint.com/sites/FaturamentoTorta', 'client_id': 'c74022f1-d1b5-47e3-913f-84d7a98cf032', 'client_secret': 'qfHtOWl6YieOhGAAavzuzUDvuf9pl2ZvD/0JSqvZhsQ=' } # Chamando conexão com API Rest context_auth = AuthenticationContext(url=app_settings['url']) context_auth.acquire_token_for_app( client_id=app_settings['client_id'], client_secret=app_settings['client_secret']) ctx = ClientContext(app_settings['url'], context_auth) # Puxando valores da lista lista_share = ctx.web.lists.get_by_title("Autorizações") items = lista_share.get_items() ctx.load(items) ctx.execute_query() for item in items: _id = '{0}'.format(item.properties["ID"]) id_autorizacao = '{0}'.format( item.properties["NumAutoriza_x00e7__x00e3_o"]) if id_autorizacao == numero_autorizacao: id_autorizacao = '{0}'.format( item.properties["NumAutoriza_x00e7__x00e3_o"]) fornecedor = '{0}'.format(item.properties["Fornecedor"]).strip() numero_ordem = '{0}'.format(item.properties["uwih"]).strip() transportador = '{0}'.format(item.properties["r9n0"]).strip() nome_motorista = '{0}'.format(item.properties["yecy"]).strip() cpf = '{0}'.format(item.properties["jcvj"]).strip() rg = '{0}'.format(item.properties["OData__x006d_vk6"]).strip() cnh = '{0}'.format(item.properties["wwof"]).strip() cavalo = '{0}'.format(item.properties["qbkd"]).strip() cavalo = cavalo.replace('-', '') minicipio_cavalo = '{0}'.format(item.properties["hr0e"]).strip() carreta_1 = '{0}'.format( item.properties["OData__x006d_cb0"]).strip() carreta_1 = carreta_1.replace('-', '') if carreta_1.upper() == 'NONE': carreta_1 = '' municipio_carreta_1 = '{0}'.format(item.properties["a8fj"]).strip() if municipio_carreta_1.upper() == 'NONE': municipio_carreta_1 = '' carreta_2 = '{0}'.format(item.properties["qdqz"]).strip() carreta_2 = carreta_2.replace('-', '') if carreta_2.upper() == 'NONE': carreta_2 = '' municipio_carreta_2 = '{0}'.format( item.properties["OData__x0071_aw9"]).strip() if municipio_carreta_2.upper() == 'NONE': municipio_carreta_2 = '' tipo_veiculo = '{0}'.format(item.properties["OData__x0065_op5"]) procedimento_especial = '{0}'.format(item.properties["i0dv"]) numero_eixos = '{0}'.format(item.properties["ahpu"]) quantidade_ordens = '{0}'.format(item.properties["hpzf"]) geradas = '{0}'.format(item.properties["OData__x006d_kv6"]) data_inicio = '{0}'.format(item.properties["OData__x0068_qp8"]) data_final = '{0}'.format(item.properties["OData__x0078_od1"]) data_execucao = '{0}'.format(item.properties["ejtw"]) ativo = '{0}'.format(item.properties["ATIVA"]) autoriazacao = AutorizacaoSharePoint() autoriazacao.id_autorizacao = id_autorizacao autoriazacao.fornecedor = fornecedor autoriazacao.numero_ordem = numero_ordem autoriazacao.transportador = transportador autoriazacao.nome_motorista = nome_motorista autoriazacao.cpf = cpf autoriazacao.rg = rg autoriazacao.cnh = cnh autoriazacao.cavalo = cavalo autoriazacao.minicipio_cavalo = minicipio_cavalo autoriazacao.carreta_1 = carreta_1 autoriazacao.municipio_carreta_1 = municipio_carreta_1 autoriazacao.carreta_2 = carreta_2 autoriazacao.municipio_carreta_2 = municipio_carreta_2 autoriazacao.tipo_veiculo = tipo_veiculo autoriazacao.procedimento_especial = procedimento_especial autoriazacao.numero_eixos = numero_eixos autoriazacao.quantidade_ordens = quantidade_ordens autoriazacao.geradas = geradas autoriazacao.data_inicio = data_inicio autoriazacao.data_final = data_final autoriazacao.data_execucao = data_execucao autoriazacao.ativo = ativo autoriazacao._id = _id return autoriazacao return None