Skip to content

Instantly share code, notes, and snippets.

@KarimKamaletdinov
Created June 9, 2024 16:32
Show Gist options
  • Save KarimKamaletdinov/cbf6391b13c6536bff3c054f77e1b5a5 to your computer and use it in GitHub Desktop.
Save KarimKamaletdinov/cbf6391b13c6536bff3c054f77e1b5a5 to your computer and use it in GitHub Desktop.
A program to upload documents on Google Drive and then open them with Google Docs
import os
import sys
import webbrowser
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
# Читаем аргументы командной строки, пропускаем первый (название самой проги)
arg = ' '.join(sys.argv[1:])
# SCOPES - API google, используемые нами - только гугл диск
SCOPES = ['https://www.googleapis.com/auth/drive']
# Права. Сейчас их нет. Далее мы их получим
creds = None
# Если права уже сохранены, достанем из файла
if os.path.exists("/home/karim/dev/gdo/token.json"):
creds = Credentials.from_authorized_user_file("/home/karim/dev/gdo/token.json", SCOPES)
if creds and creds.expired:
creds.refresh(Request()) # Устарели - обновим
# Права не сохранены - юзер войдёт в аккаунт гугл и даст их нам
else:
creds = InstalledAppFlow.from_client_secrets_file(
"/home/karim/dev/gdo/credentials.json", SCOPES
).run_local_server(port=0)
# Сохраним
with open("/home/karim/dev/gdo/token.json", "w") as f:
f.write(creds.to_json())
# Подключимся к гугл диску
service = build('drive', 'v3', credentials=creds)
# И файл туды
file = service.files().create(body={"name": arg.split('/')[-1]}, media_body=MediaFileUpload(arg), fields="id").execute()
# Выбираем приложение гугла в зависимости от типа файла
google_app = 'spreadsheets' if '.xls' in arg else 'presentation' if 'ppt' in arg else 'document'
# Открываем закинутый нами на гугл диск файл в нужном приложении в браузере
webbrowser.open(f'https://docs.google.com/{google_app}/d/{file["id"]}/edit')
@KarimKamaletdinov
Copy link
Author

Can be compiled to executable and installed as system default app for docx, xlsx, pptx files. You have to replace local token and credentials wiles locations with absolute urls on your computer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment