I am trying to read a file from sharepoint using the office 365 package. My code looks like this:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
app_settings = {
'url': 'https://xxxx.sharepoint.com/sites/mysite/',
'client_id': 'id',
'client_secret': 'secret'}
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)
File.open_binary(ctx, '/sites/mysite/Documents/Dictionary.csv')
I've tried several variations of the server relative url and get the error every time:
MissingSchema: Invalid URL "<bound method ClientContext.service_root_url of
<office365.sharepoint.client_context.ClientContext object at
0x00019D2CCED68>>web/getfilebyserverrelativeurl
('/sites/mysite/Documents/Dictionary.csv')/\\$value": No schema supplied.
Perhaps you meant http://<bound method ClientContext.service_root_url of
<office365.sharepoint.client_context.ClientContext object at
0x00019D2CCED68>>web/getfilebyserverrelativeurl('/sites/mysite/Documents/Dictionary.csv')/\$value?
Is there a simple way to read and download files from sharepoint online using the office365 library?
Related
I am trying to read an excel file from SharePoint to python and I get the following error:
ValueError: Excel file format cannot be determined, you must specify an engine manually.
The python script goes something like that:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import pandas as pd
url = "https://company.sharepoint.com/:x:/r/sites/A_team/"
username = 'myemail#mail.com'
password = 'password'
relative_url = "sites/A_team/Documents_python/Folder/Book.xlsx"
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Authentication successful")
else:
print(ctx_auth.get_last_error())
response = File.open_binary(ctx, relative_url)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start
pd.read_excel(bytes_file_obj)
Does anyone have an idea what should I do?
I tried to add an engine, but then I get the following error:
BadZipFile: File is not a zip file
I'm trying to use the sandbox from https://fhir.epic.com/ for Backend Services.
I am following this tutorial : https://fhir.epic.com/Documentation?docId=oauth2§ion=BackendOAuth2Guide :
I already register a new app, created a JWT (using SSL keys) tested the JWT on https://jwt.io/ : works fine! When I POST the JWT to the endpoint (https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token) I get an access token.
Using this access token, I can access a single patient Appointment ressource but that's it. I don't understand how to access other Resources like DiagnosticReport, Observations, etc. I added them in the scope of my App of course but still doesn't seems to work.
What am I missing here ?
This is my code where I can access the Appointment resource:
import json
from datetime import datetime, timedelta, timezone
import requests
from requests.structures import CaseInsensitiveDict
from jwt import (
JWT,
jwk_from_dict,
jwk_from_pem,
)
from jwt.utils import get_int_from_datetime
import random
import xmltodict
def main():
instance = JWT()
message = {
# Client ID for non-production
'iss': 'my_iss_here',
'sub': 'my_sub_here',
'aud': 'https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token',
'jti': f'7777-7777-7777-7777-7777{random.randint(100,1000)}',
'iat': get_int_from_datetime(datetime.now(timezone.utc)),
'exp': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(minutes=2)),
}
# Load a RSA key from a PEM file.
with open('./privatekey.pem', 'rb') as fh:
signing_key = jwk_from_pem(fh.read())
compact_jws = instance.encode(message, signing_key, alg='RS384')
headers = {}
headers['Content-Type'] = 'application/x-www-form-urlencoded'
data = {
'grant_type': 'client_credentials',
'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion': compact_jws
}
x = requests.post('https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token', headers=headers, data=data)
access_token = x.json()['access_token']
headers = {}
headers['Authorization'] = f'Bearer {access_token}'
x = requests.get('https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/STU3/Appointment/eWLhfjXHp4RUczv2om.1Ii2uiHcDc6rMEjO0xHBA3', headers=headers)
print(x.content)
When I change the request for one of these two (of the online tutorial), it doesn't work:
x = requests.get('https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4/Observation/erXuFYUfucBZaryVksYEcMg3', headers=headers)
I'm using the FHIR ID of Camilia Lopez (test patient). She supposed to have a Observation Ressource but I get an error :
<OperationOutcome xmlns="http://hl7.org/fhir"><issue><severity value="fatal" /><code value="not-found" /><details><coding><system value="urn:oid:1.2.840.114350.1.13.0.1.7.2.657369" /><code value="59008" /><display value="The FHIR ID provided was not found." /></coding><text value="The FHIR ID provided was not found." /></details><diagnostics value="Invalid FHIR ID provided" /><location value="/f:id" /><expression value="id" /></issue></OperationOutcome>
Neither of those appear to be valid FHIR IDs for the resources requested in the Epic on FHIR sandbox. The IDs in the tutorial are just examples. You should use the test data reference here for identifying Patient and other resources that are available to test with. You should also ensure you are including all the necessary headers in your calls.
I need to download a file from sharepoint using user credentials (rather that client credentials).
I've tried this:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
root_url = "https://company-my.sharepoint.com"
full_url = "https://company-my.sharepoint.com/personal/Documents/AB.csv"
ctx = ClientContext(root_url)
ctx.with_user_credentials(<my_email>,
<my_password)
response = File.open_binary(ctx, full_url)
print(response.content)
The response I am getting is
*b'{"error":{"code":"-2147024809, System.ArgumentException","message":{"lang":"en-US","value":"serverRelativePath\\r\\nParameter
name: Specified value is not supported for the serverRelativePath
parameter."}}}'*
I am trying to extract xml data from a SharePoint site.
I always get error 400. Here is my Python code.
import requests
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.http.request_options import RequestOptions
from office365.runtime.client_request import ClientRequest
from office365.graph.graph_client import GraphClient
app_settings = {
'url': 'https://xxxxxxxx.sharepoint.com/sites/xxxxxxx',
'client_id': 'xxxxxxx',
'client_secret': 'xxxxxxxx',
}
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)
token = context_auth.provider.token.accessToken
headers = {"Authorization": "Bearer " + token, "Content-type": "application/xml"}
request = requests.get("https://xxxxxxx.sharepoint.com/sites/xxxxxxx/_api/xxxxxx/xxxxx/xxxxx", headers=headers)
I don't understand what I am missing because my url seems to be correct, I can get a token, which seems to be valid and not expired. Moreover, the application I have created on the SharePoint site seems also to be correct. I have entered this code in the permission request XML:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>
The strange thing is that I can access the lists and subsites data that is available on the SharePoint site, but not this background odata.
Can someone help me please?
I am trying to download an excel file from Sharepoint with the office365 module. Here's my code.
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
app_settings = {
'url': 'https://xxxxx/sites/DownloadFiles',
'client_id': 'xxxxxx',
'client_secret': 'xxxxxx',
}
if name == 'main':
ctx_auth = AuthenticationContext(url=app_settings['url'])
ctx_auth.acquire_token_for_app(client_id=app_settings['client_id'],
client_secret=app_settings['client_secret'])
ctx = ClientContext(app_settings['url'], ctx_auth)
path = "F:\myexcel.xlsx"
response = File.open_binary(ctx, "/Shared%20Documents/myexcel.xlsx")
response.raise_for_status()
with open(path, "wb") as local_file:
local_file.write(response.content)
When I run that code, I get the following error:
400 Client Error: Bad Request for url: https://xxx/DownloadFiles/_api/web/getfilebyserverrelativeurl('/Shared%20Documents/myexcel.xlsx')/%5C$value
I am able to reproduce the same issue on my SPO.
Please modify the code as below to fix it:
response = File.open_binary(ctx, "/sites/{abc}/Shared%20Documents/source.txt")
Such as i want to download file from a site collection like "https://xxxx.sharepoint.com/sites/abc", the serverrelativeurl is "/sites/abc"
You can get the serverrelativeurl via '_spPageContextInfo' object:
And there is another SharePoint library 'shareplum' that provided some easy ways to operate files, you may have a try.
Best Regards,
Baker Kong