Изменение значения метки файла на диске Google через API PythonPython

Программы на Python
Ответить
Anonymous
 Изменение значения метки файла на диске Google через API Python

Сообщение Anonymous »

Я пытался изменить значение метки файла, используя следующий код.
Однако это не работает. У вас есть идеи?

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

# Import Libraries

import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Define the required scopes
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']

# Authenticate and load credentials
def authenticate():
creds = None
# The file token.json stores the user's access and refresh tokens.
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)  # Use the correct file name here
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())
return creds

# Main function to update the label on a file
def update_label(file_id, label_id, public_choice_id):
creds = authenticate()
service = build('drive', 'v3', credentials=creds)

try:
# Get the file's metadata including labels
file_metadata = service.files().get(fileId=file_id, fields='id,labels').execute()

# Get the existing labels
labels = file_metadata.get('labels', [])

# Update the label for 'Data Classification' to 'Public'
for label in labels:
if label['id'] == label_id:
label['value'] = public_choice_id  # Set the label value to "Public"

# Update the file with the new labels
updated_file_metadata = service.files().update(
fileId=file_id,
body={'labels': labels}
).execute()

print(f"Label for file {file_id} updated successfully!")

except HttpError as error:
print(f"An error occurred: {error}")

# Example usage
file_id = '1pXX6SPbHuEJeO8wI8LIACbfEEItIzRIz'  # The ID of the file you want to modify
label_id = 'A9438FD180'  # Data Classification label ID
public_choice_id = '66645FBAAC'  # Public choice ID for the label

update_label(file_id, label_id, public_choice_id)
Что я пробовал:
Я подтвердил, что к файлу применены метки и file_id правильный.
Я убедился, что необходимые области установлены, включая https://www.googleapis.com/auth/drive и https://www.googleapis.com/auth/drive.labels.
Я также пробовал обновить token.json и повторно -авторизация учетных данных, но проблема сохраняется.
Мне также не удалось получить текущую метку и метку значения из файла

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

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow

# SCOPES needed to access labels
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.labels']

# Authenticate and create the API client
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)

# Build the Drive API client
service = build('drive', 'v3', credentials=creds)

# Build the Labels API client
labels_service = build('drive', 'v3', credentials=creds)

# Fetch the labels for the file
file_labels = labels_service.files().get(fileId=file_id, fields='id,labels').execute()

# Check the labels associated with the file
print("File Labels:", file_labels)
Но я получаю такое сообщение:

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

HttpError: 

Подробнее здесь: [url]https://stackoverflow.com/questions/79370012/changing-a-google-drive-file-label-value-via-api-python[/url]
Ответить

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

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

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

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

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