I have been trying to implement the following procedure with python
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online#create-an-upload-session
I have been trying to get the upload URL part
Please note that I already got the access token and created the required client Id and secret
def getUploadUrl(filename="test.txt"):
global token
if (not token):
with open('token.json', 'r') as f:
token = json.load(f)
if (token["expires_at"] < time.time()):
refreshToken()
location = "/me/drive/root:/FolderA/" + filename + ":/createUploadSession"
client = OAuth2Session(client_id=client_id,
redirect_uri=REDIRECT_URI, token=token)
headers = {'Content-Type': 'application/json'}
json_file = {
"item": {"#odata.type": "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior": "replace",
"name": filename
}
}
json_string = json.dumps(json_file, indent=4)
r = client.post(BaseUrl + location,
data=json_string, headers=headers)
print(r.status_code)
print(r.text)
upload_url = ""
if(r.status_code == 200):
upload_url = r.json()['uploadUrl']
return upload_url, r
else:
return "", ""
I keep getting the following Error response though
{
"error": {
"code": "invalidRequest",
"message": "Invalid request",
"innerError": {
"request-id": "7893d0aa-fcdb-46bc-b0b6-58fd90c4cb46",
"date": "2020-03-21T17:15:13"
}
}
What I ended up doing till now is just removing
#odata.type": "microsoft.graph.driveItemUploadableProperties from the JSON payload.
Try to reload later, maybe it was the service bug.
Related
I'm currently developing an app that creates Snapchat campaigns, currently when uploading a media to an already created Media object returns the following: Media is invalid: [Fail to get image meta data for ""]
files = {'file': ("test_upload.png", 'test_upload')} url = f'https://adsapi.snapchat.com/v1/media/{media_id}/upload' response = requests.post( url=url, files=files, headers={ "Authorization": f"Bearer {snapchat_access_token}", }, )
The response:
{ "request_status": "ERROR", "request_id": "e72ba2d9-3c5c-4b0b-b3ec-13d21ab0fccd", "debug_message": "Media is invalid: [Fail to get image meta data for 3b81feaf-909c-4094-94b4-a635d065d79c]", "display_message": "We're sorry, but the data provided in the request is incomplete or incorrect", "error_code": "E2059" }
I have tested with both jpg and png.
your assisstance is highly appreciated.
Tried:
files = {'file': ("test_upload.png", 'test_upload')} url = f'https://adsapi.snapchat.com/v1/media/{media_id}/upload' response = requests.post( url=url, files=files, headers={ "Authorization": f"Bearer {snapchat_access_token}", }, )
The response:
{ "request_status": "ERROR", "request_id": "e72ba2d9-3c5c-4b0b-b3ec-13d21ab0fccd", "debug_message": "Media is invalid: [Fail to get image meta data for 3b81feaf-909c-4094-94b4-a635d065d79c]", "display_message": "We're sorry, but the data provided in the request is incomplete or incorrect", "error_code": "E2059" }
Expected: file should be uploaded successfully.
Trying to export a file from gsheet using python and I encountered this issue, may I know what I need to add on my script?
{
"error": {
"errors": [
{
"domain": "global",
"reason": "exportSizeLimitExceeded",
"message": "This file is too large to be exported."
}
],
"code": 403,
"message": "This file is too large to be exported."
}
}
Heres my script when I got the error
path = "/root/xlsx/"
prefix = "Remastered"
suffix = datetime.datetime.now().strftime("%Y%m%d")
filename = prefix + "_" + suffix + ".xlsx"
v = os.path.join(path, filename)
print(v)
with open(v, 'wb') as f:
f.write(res.content)
Please modify url and test it again.
From:
url = "https://www.googleapis.com/drive/v3/files/" + "sdfasdasdasdasdadsa_1231_123" + "/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet"
To:
url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=###YourSpreadsheetId###"
I'm using the AWS lambda function to send alerts to our slack channel. But, due to some unknown issue, I'm not getting slack alert and not even getting any kind of error message from the AWS lambda function. Logs represent that the function ran successfully without any error but I do not receipt any alert
code:
import json, sys, csv, os
import requests
def lambda_handler(event, context):
def Send2Slack(message):
if __name__ == '__main__':
print('inside slack function')
url = "webhook_URL"
title = (f"New Incoming Message")
slack_data = {
"username": "abc",
"channel" : "xyz",
"attachments": [
{
"color": "#ECB22E",
"fields": [
{
"title": title,
"value": message,
"short": "false",
}
]
}
]
}
byte_length = str(sys.getsizeof(slack_data))
headers = {'Content-Type': "application/json", 'Content-Length': byte_length}
response = requests.post(url, data=json.dumps(slack_data), headers=headers)
if response.status_code != 200:
raise Exception(response.status_code, response.text)
output = "Hello Slack "
Send2Slack(output)
Please let me know where I'm doing wrong and help me fix this issue.
I'm able to answer this issue.
def Send2Slack(message):
if __name__ == '__main__':
Once I removed if __name__ == '__main__': from send2slack function the it worked.
Otherwise, I was not able to get into the function.
Thanks for all your help.
Code that logs in from flask as discord oauth2 and receives logged-in user information.
However, log-in is successful only under few discord accounts.
The rest of the accounts have 401 errors like that.
I don't know why I can only log in properly from Few accounts and not from another.
my flask code :
from flask import Flask, request, render_template, redirect, session
from oauth import Oauth
app = Flask(__name__)
#app.route("/")
def index():
return redirect(Oauth.discord_login_url)
#app.route("/login")
def login():
code = request.args.get("code")
access_token = Oauth.get_access_token(code)
user_json = Oauth.get_user_json(access_token)
username = user_json.get("username")
return username
if(__name__ == "__main__"):
app.run(host="0.0.0.0", port=8080)
oauth.py :
import requests
class Oauth(object):
client_id = ...
client_secret = ...
scope = "email"
redirect_uri = "http://192.168.35.5:8080/login"
discord_login_url = f"https://discord.com/api/oauth2/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&scope={scope}"
discord_token_url = "https://discord.com/api/oauth2/token"
discord_api_url = "http://discord.com/api"
#staticmethod
def get_access_token(code):
payload = {
"client_id": Oauth.client_id,
"client_secret": Oauth.client_secret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": Oauth.redirect_uri,
"scope": Oauth.scope,
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
acces_token = requests.post(
url=Oauth.discord_token_url, data=payload, headers=headers
)
print(acces_token)
print(acces_token.text)
json = acces_token.json()
return json.get("access_token")
#staticmethod
def get_user_json(access_token):
print(access_token)
url = Oauth.discord_api_url + "/users/#me"
data = {
"scope": Oauth.scope
}
headers = {"Authorization": f"Bearer {access_token}"}
user_object = requests.get(url=url, data=data, headers=headers)
print(user_object)
print(user_object.text)
user_json = user_object.json()
return user_json
print :
<Response [200]>
{"access_token": "rE2pOOJLn2rhpCxyEaKuYko0UDOG7N", "expires_in": 604800, "refresh_token": "HMSTtbeKXIbwSvrubBQfw9nkHu9cyu", "scope": "email", "token_type": "Bearer"}
rE2pOOJLn2rhpCxyEaKuYko0UDOG7N
<Response [401]>
{"message": "401: Unauthorized", "code": 0}
test in ubuntu shell:
root#localhost:~# curl --location --request GET 'http://discord.com/api/users/#me' --header 'Authorization: Bearer RV41u
drW040OZGzzZO3rvI1hVyZO4n'
# this account is working
{"id": "349781935196995585", "username": "Obtuse triangle", "avatar": "d57820246e2726d6b0f703ff216252d9", "discriminator": "5343", "public_flags": 64, "flags": 64, "banner": null, "banner_color": null, "accent_color": null, "locale": "en-US
root#localhost:~# curl --location --request GET 'http://discord.com/api/users/#me' --header 'Authorization: Bearer rE2pOOJLn2rhpCxyEaKuYko0UDOG7N'
# but this account is working
{"message": "401: Unauthorized", "code": 0}
From Discord's documentation:
Returns the user object of the requester's account. For OAuth2, this requires the identify scope, which will return the object without an email, and optionally the email scope, which returns the object with an email.
Try adding the identify scope to your token request
my name is Adrian. I want to add user to the G suite via google admin SDK via python3.
here is my problem:
I have this code:
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
def createUserConnection():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token, encoding='Latin-1')
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
createUserConnection.service = build('admin', 'directory_v1', credentials=creds)
def addUser(name,familyName,usermail):
print('Adding user '+usermail+' to the G suite')
#json definition
userInfo = json.dumps({
"name" : {
"givenName": name,
"familyName": familyName
},
"kind": "admin#directory#user",
"primaryEmail": usermail,
"password": "Welcome1234",
"changePasswordAtNextLogin": True
})
createUserConnection.service.users().insert(body=userInfo).execute()
if __name__ == '__main__':
createUserConnection()
addUser("bla","bla","blabla#24i.com")
When i run it via python3, it rerurns an error. File "/Users/adrianbardossy/Downloads/google_accounts/python3.7/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Invalid Input: primary_user_email">
I was trying to fix by passing the username blabla instead of blabla#24i.com, still the same issue. Based on the documentation here: https://developers.google.com/resources/api-libraries/documentation/admin/directory_v1/python/latest/admin_directory_v1.users.html for the insert method. Can you help me resolve the issue?
Adrian
This is caused by inputting a JSON object string in the body argument to service.users().insert(). It should just be a plain python dict.
Instead of
userInfo = json.dumps({
"name": ...
use
userInfo = {
"name": ...
I was also stuck on this for a long time since the docs imply it should be entered as a JSON object, which I interpreted to mean "JSON object encoded as a string", but i discovered it should really just be a python object/dict.
I had the same message error Invalid Input: primary_user_email using the javascript library and from what I understand it means the api couldn't find the primaryEmail property in your body. In other words: your JSON is malformed.
Here's my take on this issue, I use the javascript terminology but it should transfer to python as well :
If you're using the gapi.client.directory.insert method of adding a user you need to encapsulate your body in a resource property, your JSON becomes
{
"resource": {
"name" : {
"givenName": "name",
"familyName": "familyName"
},
"kind": "admin#directory#user",
"primaryEmail": "usermail",
"password": "password",
"changePasswordAtNextLogin": true
}
}
However, if you're using the gapi.client.request method of adding a user, the library will encapsulate the JSON for you, so your body should look like this :
{
"name" : {
"givenName": "name",
"familyName": "familyName"
},
"kind": "admin#directory#user",
"primaryEmail": "usermail",
"password": "password",
"changePasswordAtNextLogin": true
}
Short answer for OP: you're using the insert method, try encapsulating your JSON in a resource property.
Hope it helps people who stumble on this error in the future
I know this is old, but if you haven’t gotten it yet, I threw a dict into the field in lieu of doing any conversion or anything to JSON:
def get_user_inf(service):
'''
This initiates the collection of user data.
'''
user_fname = str(input('What is the new hires first name? : '))
user_lname = str(input('What is the new hires last name? : '))
user_email = str(input('What is the new hires email? : '))
new_user = {
"name": {
"givenName": user_fname,
"fullName": user_fname + " " + user_lname,
"familyName": user_lname,
},
"primaryEmail": user_fname + '.' + user_lname + "#hometownticketing.com",
"recoveryEmail": user_email,
"password": "Temp42!!!",
"changePasswordAtNextLogin": True,
}
user = service.users().insert(body=new_user).execute()