Created
March 29, 2023 05:15
-
-
Save OhkuboSGMS/764e49a2cd4c4c73963b871ac8a318e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydrive2.drive import GoogleDrive | |
from pydrive2.auth import GoogleAuth | |
#https://docs.iterative.ai/PyDrive2/filemanagement/#upload-file-to-a-specific-folder | |
def login_with_service_account(): | |
""" | |
Google Drive service with a service account. | |
note: for the service account to work, you need to share the folder or | |
files with the service account email. | |
:return: google auth | |
""" | |
# Define the settings dict to use a service account | |
# We also can use all options available for the settings dict like | |
# oauth_scope,save_credentials,etc. | |
settings = { | |
"client_config_backend": "service", | |
"service_config": { | |
"client_json_file_path": "drive_service.json", | |
} | |
} | |
# Create instance of GoogleAuth | |
gauth = GoogleAuth(settings=settings) | |
# Authenticate | |
gauth.ServiceAuth() | |
return gauth | |
def upload_file_google_drive(): | |
auth = login_with_service_account() | |
drive = GoogleDrive(auth) | |
file1 = drive.CreateFile({'title': 'Hello.txt', | |
'parents': [ | |
{'id': '<folder_id>'} | |
]}) | |
file1.SetContentString('Hello') | |
file1.Upload() # Files.insert() | |
print(file1) | |
print('title: %s, id: %s' % (file1['title'], file1['id'])) | |
file_list = drive.ListFile({'q': "'root' in parents"}).GetList() | |
for file1 in file_list: | |
print('title: {}, id: {}'.format(file1['title'], file1['id'])) | |
if __name__ == '__main__': | |
upload_file_google_drive() | |
""" | |
1. アップロードするDriveのフォルダを決める | |
2. URLからフォルダのIDを取得する | |
3. Google Drive APIを有効にしたサービスアカウントを発行する | |
4. サービスアカウントのメールアドレスをフォルダの共有アカウントに追加する | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment