[Python] Google Auth Service Account Bearer Photo API

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to upload an image to google photos service using a google service account with a domain-wide delegation to use a user@domain.com account.

    Somehow I only get a 401 error: "Authentication session is not defined." using the code below

    What am I doing wrong?

    CODE:

    class GooglePhotosApi:
    def __init__(self):
    self.SERVICE_ACCOUNT_FILE = (
    os.path.dirname(os.path.abspath(__file__)) + "/service_account.json"
    )
    self.SCOPES = [
    "https://www.googleapis.com/auth/photoslibrary",
    "https://www.googleapis.com/auth/photoslibrary.sharing",
    "https://www.googleapis.com/auth/photoslibrary.appendonly",
    "https://www.googleapis.com/auth/iam",
    "https://www.googleapis.com/auth/cloud-platform",
    ]



    def auth_service_account(self):
    self.credentials = service_account.Credentials.from_service_account_file(
    self.SERVICE_ACCOUNT_FILE,
    scopes=self.SCOPES,
    subject="*user@domain.com*",
    )

    self.access_token = self.credentials._make_authorization_grant_assertion()
    return self.credentials


    def upload_media(self, img):
    self.service = discovery.build(
    "photoslibrary", "v1", credentials=self.credentials, static_discovery=False
    )

    # step 1: Upload byte data to Google Server
    image_dir = os.path.dirname(os.path.abspath(__file__)) + "/"
    upload_url = "https://photoslibrary.googleapis.com/v1/uploads"

    headers = {
    # "Authorization": "Bearer {}".format(self.access_token.decode("utf-8")),
    "Authorization": "Bearer " + str(self.access_token),
    "Content-type": "application/octet-stream",
    "X-Goog-Upload-Protocol": "raw",
    }

    image_file = os.path.join(image_dir, "img.jpg")
    headers["X-Goog-Upload-File-Name"] = "img.jpg"

    img = open(image_file, "rb").read()
    response = requests.post(upload_url, data=img, headers=headers)

    request_body = {
    "newMediaItems": [
    {
    "description": "Static Name",
    "simpleMediaItem": {
    "uploadToken": response.content.decode("utf-8")
    },
    }
    ]
    }

    upload_response = (
    self.service.mediaItems().batchCreate(body=request_body).execute()
    )

    return upload_response


    These are the domains for the domain-wide delegation:


    Continue reading...

Compartilhe esta Página