Как загрузить фотографию контакта домена в Google Workspace?Python

Программы на Python
Ответить
Anonymous
 Как загрузить фотографию контакта домена в Google Workspace?

Сообщение Anonymous »

У меня есть код Python для обновления фотографии контакта с помощью API Google People. Это работает для контакта пользователя, но я не могу заставить его работать для контактов домена.

Код: Выделить всё

from __future__ import print_function

import os.path
import base64

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user',
"https://www.googleapis.com/auth/contacts", "https://www.googleapis.com/auth/directory.readonly"]

def jpg_to_base64(file_path):
"""
Converts a JPEG file to a Base64-encoded string.

Args:
file_path (str): The path to the JPEG file.

Returns:
str: The Base64-encoded string.
"""
try:
with open(file_path, "rb") as image_file:
# Read the file in binary mode
image_data = image_file.read()

# Encode the binary data to Base64 bytes
encoded_bytes = base64.b64encode(image_data)

# Decode the bytes to a UTF-8 string
base64_string = encoded_bytes.decode('utf-8')

return base64_string
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None

def main():
"""Shows basic usage of the Admin SDK Directory API.
Prints the emails and names of the first 10 users in the domain.
"""

# Read a JPEG file into a Base64 string

pic = jpg_to_base64('C:\\Users\\daveb\\Downloads\\images\\img138.jpg')

print(f"Bytes in file: {len(pic)}")

creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())

# Call the People API
request_body = {
"photoBytes": pic,
"personFields": "names",
#       "sources": "READ_SOURCE_TYPE_CONTACT"
"sources": "READ_SOURCE_TYPE_DOMAIN_CONTACT"
}
# You can add more requests to the list

service2 = build("people", "v1", credentials=creds)
print("Attempt to update a photo")
results1 = service2.people().updateContactPhoto(
resourceName='people/dCAUY6tTu1ujGxflCMhUxMDM4NDEwODkyMTc3NjgwNDU4MDU',
#       resourceName='people/c2670880152513360950',
body=request_body).execute()

picresp = results1.get("person", [])

print(
f"resourceName: {picresp['resourceName']}, DisplayName: {picresp['names'][0]['displayName']} ")

if __name__ == '__main__':
main()
Когда я меняю источник запроса с READ_SOURCE_TYPE_CONTACT на READ_SOURCE_TYPE_DOMAIN_CONTACT и использую ресурс контактного лица домена, я получаю следующую ошибку:

Код: Выделить всё

Exception has occurred: HttpError

File "C:\Users\daveb\Documents\Python\Hello World\Photo.py", line 90, in main
body=request_body).execute()
~~~~~~~^^
File "C:\Users\daveb\Documents\Python\Hello World\Photo.py", line 99, in 
main()
~~~~^^
googleapiclient.errors.HttpError: 
Я получаю ресурс «Люди» из другой программы Python, которая перечисляет контакты с помощью API людей и возвращает ресурс контактного лица. Как я могу заставить это работать?


Подробнее здесь: https://stackoverflow.com/questions/798 ... -workspace
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»