I'm transitioning to the new admin-sdk api's and not finding it easy. I've figured out oath and a basic user lookup, but now I am stuck on creating a google apps account.
Here's the code I am using:
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
SERVICE_ACCOUNT_EMAIL = 'xyz#developer.gserviceaccount.com'
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12'
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL,
key,
scope='https://www.googleapis.com/auth/admin.directory.user',
sub='myadmin#mydomain.edu',
)
http = httplib2.Http()
http = credentials.authorize(http)
userinfo = { 'primaryEmail': 'jane#mydomain.edu',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': 'mypasswd',
}
service = build("admin", "directory_v1", http=http)
users = service.users()
users.insert(userinfo).execute()
And here is the result:
Traceback (most recent call last):
File "xy", line 39, in <module>
new_user = users.insert(userinfo ).execute()
TypeError: method() takes exactly 1 argument (2 given)
I have tried a lot of permutations on this theme to no avail, including:
users.insert(name='Jane Smith', password='mypasswd', name.familyName='Smith',
name.givenName='Jane', primaryEmail='jane#testg.berkeley.edu').execute()
SyntaxError: keyword can't be an expression
users.insert(name='Jane Smith', password='mypasswd', familyName='Smith',
givenName='Jane', primaryEmail='jane#testg.berkeley.edu').execute()
File "build/bdist.linux-x86_64/egg/apiclient/discovery.py", line 573, in method
TypeError: Got an unexpected keyword argument "givenName"
Any help would be greatly appreciated.
Try:
userinfo = {'primaryEmail': 'jane#mydomain.edu',
'name': { 'givenName': 'Jane', 'familyName': 'Smith' },
'password': 'mypasswd',
}
service = build("admin", "directory_v1", http=http)
service.users().insert(body=userinfo).execute()
Related
I'm trying to remove users from an audience in the Facebook Ads API, using the delete_users function.
This is my code so far:
'''
from collections import UserList
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi
from facebook_business.api import FacebookRequest
access_token = 'XXX'
id = 'XXX'
api = FacebookAdsApi.init(access_token=access_token)
fields = []
params = {
'name': 'Test Audience',
'subtype': 'CUSTOM',
'description': 'People who purchased on my website',
'customer_file_source': 'USER_PROVIDED_ONLY',
}
print ( AdAccount(id).create_custom_audience(
fields=fields,
params=params,
) )
fields = []
params = {
'name': 'Test Audience',
'payload': hashed_list_of_emails
}
CustomAudience.delete_users(
self
fields=fields,
params=params,
method='DELETE',
endpoint='/users',
)
'''
I am receiving an error which tells me to replace self with node_id=self['id'], but I am unclear on what this is. I am also unclear on which part of the delete_users function should contain the audience_id, and where to insert the payload of the list of hashed email to remove from the audience.
I am trying to pass multiple parameters to hotel offers using the Amadeus Python SDK but I am getting a 400 error code. How can I include checkInDate and checkOutDate in the request?
here's the code :
amadeus = Client(
client_id = clientID,
client_secret = ClientSecret
)
try:
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=citycode,checkInDate=checkindate,checkOutDate=checkoutdate,adults=adults,roomQuantity=rooms)
k = hotels_by_city.data
print(k)
Here an example of how to use the Python SDK to implement Hotel Search and Book:
# Install the Python library from https://pypi.org/project/amadeus
from amadeus import Client, ResponseError
amadeus = Client(
client_id='YOUR_AMADEUS_API_KEY',
client_secret='YOUR_AMADEUS_API_SECRET'
)
try:
# Get list of Hotels by city code
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode='PAR', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Get list of offers for a specific hotel
hotel_offers = amadeus.shopping.hotel_offers_by_hotel.get(hotelId = 'HSMADAMI', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Confirm the availability of a specific offer
offer = hotel_offers.data['offers'][0]['id']
offer_availability = amadeus.shopping.hotel_offer(offer).get()
guests = [{'id': 1, 'name': { 'title': 'MR', 'firstName': 'BOB', 'lastName': 'SMITH' }, 'contact': { 'phone': '+33679278416', 'email': 'bob.smith#email.com'}}]
payments = { 'id': 1, 'method': 'creditCard', 'card': { 'vendorCode': 'VI', 'cardNumber': '4151289722471370', 'expiryDate': '2021-08' } }
hotel_booking = amadeus.booking.hotel_bookings.post(offer, guests, payments)
print(hotel_booking.data)
except ResponseError as error:
raise error
the documentation:
https://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
from xmlrpc.client import ServerProxy
url = 'http://api.opensubtitles.org/xml-rpc'
server = ServerProxy(url)
token = server.LogIn('username', 'Password', 'eng', 'TemporaryUserAgent')['token']
data = server.SearchSubtitles(token, [{'sublanguageid': 'english', 'query': 'Movie Name'}])
I print data and it has IDSubtitleFile in it. but then I try
id_subtitle_file = data.get('IDSubtitleFile')
and it prints None
I have seen it done this way too
id1= data.get('data')
subtitle_id = id1.get('IDSubtitleFile'))
but this throws 'list' object has no attribute 'get'
what am I doing wrong?
Please check the API documentation: here
The search request response structure:
{
status: ...
data: [ # <-- array
...records...
]
}
Code sample below:
from xmlrpc.client import ServerProxy
server = ServerProxy("http://api.opensubtitles.org/xml-rpc")
token = server.LogIn('username', 'pass', 'eng', 'TemporaryUserAgent')['token']
response = server.SearchSubtitles(token,
[{'sublanguageid': 'english', 'query': 'Movie Name'}]
)
for record in response["data"]:
print(record["IDSubtitleFile"])
I am trying to run a code similar to the one in this question: How do I sign a POST request using HMAC-SHA512 and the Python requests library?
I have the following code:
import requests
import hmac
import hashlib
from itertools import count
import time
headers = { 'nonce': '',
'Key' : 'myKey',
'Sign': '',}
payload = { 'command': 'returnCompleteBalances',
'account': 'all'}
secret = 'mySecret'
NONCE_COUNTER = count(int(time.time() * 1000))
headers['nonce'] = next(NONCE_COUNTER)
request = requests.Request(
'POST', 'https://poloniex.com/tradingApi',
params=payload, headers=headers)
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
request.headers['Sign'] = signature.hexdigest()
with requests.Session() as session:
response = session.send(request)
The following line :
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
Throws this error: 'Request' object has no attribute 'body'
Your source code has several problems:
For the POST method you can't use the argument params, but you need the argument data.
As mentioned before, you need the .prepare() method.
The parameter nonce needs to be specified also in payload, not in headers.
This should work:
import requests
import hmac
import hashlib
from itertools import count
import time
NONCE_COUNTER = count(int(time.time() * 1000))
headers = { 'Key' : 'myKey',
'Sign': '',}
payload = { 'nonce': next(NONCE_COUNTER),
'command': 'returnCompleteBalances',
'account': 'all'}
secret = 'mySecret'
request = requests.Request(
'POST', 'https://poloniex.com/tradingApi',
data=payload, headers=headers).prepare()
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512)
request.headers['Sign'] = signature.hexdigest()
with requests.Session() as session:
response = session.send(request)
I'm trying to upload a picture to a python-eve server using the requests library. In order to do that, I send a multipart/form-data request. This seems to be a problem for my schema, which looks like this:
schema = {
'name': {
'type': 'string',
'required': True
},
'description': {
'type': 'string'
},
'picture': {
'type': 'media'
},
'properties': {
'type' : 'dict'
}
}
The request looks like this:
import requests
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})
What I get is a ResourceInvalid exception:
ResourceInvalid: Failed. Response status: 422. Response message: UNPROCESSABLE ENTITY. Error message: {"_status": "ERR", "_issues": {"properties": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}}
Is there any solution for this? Am I missing something about the request format?
Something like this should work just fine:
import requests
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello'}
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})
I have just had a similar issue. I suggest you try to change your code this way: dump your dictionary into a json object, and add an header to describe the content you are sending.
import requests
import json
file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
headers = {'Content-type': 'application/json; charset=utf-8'}
r = requests.post("http://localhost:5001/node", data=json.dumps(payload), files={'picture': file}, headers=headers)