How to upload a file to onedrive as a specific user? - python

I am trying to upload files to a user OneDrive as that user.
I successfully registered my app and granted the correct permissions.
I am able to upload files to a user drive but only as application and not as the user.
I was able to do the same on google drive using google sdk which allow user impersonation.
I could not find any decent documentation on user impersonation for OneDrive.
import requests
params = {
'grant_type':'client_credentials',
'client_id': 'xxx',
'client_secret': 'yyy',
'resource':'https://graph.microsoft.com'
}
r = requests.post('https://login.microsoftonline.com/{tenant-id}/oauth2/token', data=params, verify=False)
token = r.json()['access_token']
headers = {
'Authorization':token
}
fileHandle = open('somefile.txt', 'rb')
r = requests.put('https://graph.microsoft.com/v1.0/users/{user-id}/drive/items/root:/somefile.txt:/content',
headers=headers, data=fileHandle, verify=False)
fileHandle.close()
this is part of the response I get showing the file was created/modified by my application which make sense:
'createdBy': {
'application': {
'id': 'xxx',
'displayName': 'my_app'
}
},
'lastModifiedBy': {
'application': {
'id': 'xxx',
'displayName': 'my_app'
}
},
my goal is to have my app impersonate my users to create/modify the files.
Is this even supported with onedrive api?

Related

How to replace file in google drive using google drive API, Fix Error In google Drive API *fileIdInUse*

It's been a while since I've worked with the Google Drive API. And I want to replace files using Google Drive API. I want to do that only using the Python HTTP requests module. Unfortunately, I always encounter an error. Could you please respond to this? It would be greatly appreciated.
CODE:
filedirectory = './Test.txt'
filename = 'Test.txt'
folderid = 'XXXXX'
updateFileId = 'XXXX'
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'id':updateFileId,
'fileId': updateFileId,
'name': filename,
'parents':[folderid]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./Test.txt", "rb"),
}
r2= requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers= headers,
files= files,
)
Error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "fileIdInUse",
"message": "A file already exists with the provided ID."
}
],
"code": 409,
"message": "A file already exists with the provided ID."
}
}
<Response [409]>
It would be extremely helpful if you could assist me with this issue.
You are using the wrong end point and the wrong HTTP type.
You are using the Files.create end point.
requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers= headers,
files= files,
To update an existing file you use Files.update
Which is a HTTP PATCH call and requires that you send the file id.
PATCH https://www.googleapis.com/upload/drive/v3/files/fileId
You need to remember to pass the id in the request. note the fileId part in the request above.
filedirectory = './Test.txt'
filename = 'Test.txt'
folderid = 'XXXXX'
updateFileId = 'XXXX'
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'name': filename,
'parents':[folderid]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./Test.txt", "rb"),
}
r2= requests.patch(
"https://www.googleapis.com/upload/drive/v3/files/" + updateFileId + "?uploadType=multipart",
headers= headers,
files= files,
)

How to set the Doc Id with Firebase REST API

Is there a way to manually create a docId when inserting a document into Firestore?
The following Python3 code will insert a new document in Firestore with an auto-generated docId.
import requests
import json
project_id = 'MY_PROJECT_NAME'
web_api_key = 'MY_WEB_API_KEY'
collection_name = 'MY_COLLECTION_NAME'
url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}/?key={web_api_key}'
payload = {
'fields': {
'title': { 'stringValue': 'myTitle' },
'category': { 'stringValue': 'myCat' },
'temperature': { 'doubleValue': 75 }
}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
response_dict = json.loads(response.content)
for i in response_dict:
print(f'{i}: {response_dict[i]}')
In case anyone else wants to use this code in the future, to get a Web API key, go to Google Cloud Platform > APIs & Services > Credentials > Create Credentials > API key, then copy the value it generates here.
Thanks,
Ryan
answered in Google Cloud Firestore REST API createDocument auto genarates ID documentId should be added as a query parameter when document is created
So for the code in the question, just url should be changed with the same body:
url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}?documentId={your_custom_doc_id}&key={web_api_key}'
To set a custom document ID, you only need to append the name to the URL path after the respective collection. This is similar to how the document reference works where the path must point to the desired location.
From the documentation:
https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA

FCM push notifications not working in AWS Lambda using Python

I didn't find any questions that solved my issue, hence below:
This is the code I am using to send an FCM push notification via AWS Lambda written in Python. The AWS code is deployed on Lambda using the Zappa package:
# SENDING FCM NOTIFICATION
notification_headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body_en = {
'notification': {
'title': post['src'],
'body': post['title'],
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'sound': 'default'
},
'to': deviceToken,
'priority': 'high',
'content_available': 'true',
}
response_en = requests.post(
"https://fcm.googleapis.com/fcm/send",
headers = notification_headers,
data = json.dumps(body_en)
)
return response_en
Are there any imports I must do before being able to use FCM in AWS Lambda?

Xero API not working for Accounts in python

I am trying to call xero Accounts api in python but not working for some reason. It works well for the rest of APIs such as Invoices, reports, and so on, but Accounts.
The following script is my python script i am using to call the api.
get_url = 'https://api.xero.com/api.xro/2.0/Accounts'
response = requests.get(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
})
json_response = response.json()
print(json_response)
But this is throwing the following error:
{'Type': None, 'Title': 'Unauthorized', 'Status': 401, 'Detail': 'AuthorizationUnsuccessful', 'Instance': '3c1649ef-6eed-4e64-8503-04fc99481db2', 'Extensions': {}}
Can anyone tell me why this is happening? why just Accounts?
Can you share what scopes you're requesting? https://developer.xero.com/documentation/oauth2/scopes
Invoices requires accounting.transactions
Reports requires accounting.reports.read
Accounts requires accounting.settings

How do I call the Google Vision API with an image stored in Google Cloud Storage?

I have a bunch of pictures on GCS and would like to figure out what they are?
For GCS Integration - I would just modify the above body to point to the GCS location by replacing content attribute with gcs_image_uri
batch_request = [{
'image': {
'source': {
'gcs_image_uri': "gs://bucket_name/object_path"
}
},
'features': [{
'type': 'LANDMARK_DETECTION',
'maxResults': max_results,
}]
}]
service = get_vision_service()
request = service.images().annotate(body={
'requests': batch_request,
})
response = request.execute()
The Vision API can be accessed via a REST API call. You pass in a JSON request with either image embedded or a link to the image in GCS. You can then pass in the features you want to run on the image. This is passed in as a JSON request and the response object contains the annotations. Here is a snippet of Python code calling the Vision API.
DISCOVERY_URL='https://{api}.googleapis.com/$discovery/rest?version={apiVersion}'
credentials = GoogleCredentials.get_application_default()
service = discovery.build('vision', 'v1', credentials=credentials,
discoveryServiceUrl=DISCOVERY_URL)
with open(photo_file, 'rb') as image:
image_content = base64.b64encode(image.read())
service_request = service.images().annotate(
body={
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'LABEL_DETECTION', # Feature to detect
'maxResults': 1,
}]
}]
})
response = service_request.execute()
label = response['responses'][0]['labelAnnotations'][0]['description']
For additional information, you might wish to look at the Label Detection Tutorial

Categories

Resources