|
| 1 | +# Copyright 2021 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START forms_duplicate_form] |
| 16 | +from __future__ import print_function |
| 17 | +import os.path |
| 18 | +from googleapiclient.discovery import build |
| 19 | +from google_auth_oauthlib.flow import InstalledAppFlow |
| 20 | +from google.auth.transport.requests import Request |
| 21 | +from google.oauth2.credentials import Credentials |
| 22 | + |
| 23 | +# If modifying these scopes, delete the file token.json. |
| 24 | +SCOPES = ['https://www.googleapis.com/auth/drive'] |
| 25 | + |
| 26 | +def main(): |
| 27 | + """Shows copy file example in Drive v3 API. |
| 28 | + Prints the name, id and other data of the copied file. |
| 29 | + """ |
| 30 | + creds = None |
| 31 | + if os.path.exists('token.json'): |
| 32 | + creds = Credentials.from_authorized_user_file('token.json', SCOPES) |
| 33 | + # If there are no (valid) credentials available, let the user log in. |
| 34 | + if not creds or not creds.valid: |
| 35 | + if creds and creds.expired and creds.refresh_token: |
| 36 | + creds.refresh(Request()) |
| 37 | + else: |
| 38 | + flow = InstalledAppFlow.from_client_secrets_file( |
| 39 | + 'client_secrets.json', SCOPES) |
| 40 | + creds = flow.run_local_server(port=0) |
| 41 | + # Save the credentials for the next run |
| 42 | + with open('token.json', 'w') as token: |
| 43 | + token.write(creds.to_json()) |
| 44 | + |
| 45 | + service = build('drive', 'v3', credentials=creds) |
| 46 | + |
| 47 | + # Call the Drive v3 API |
| 48 | + origin_file_id = '1ox-6vHFeKpC6mon-tL5ygBC8zpbTnTp76JCZdIg80hA' # example ID |
| 49 | + copied_file = {'title': 'my_copy'} |
| 50 | + results = service.files().copy( |
| 51 | + fileId=origin_file_id, body=copied_file).execute() |
| 52 | + print(results) |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + main() |
| 56 | +# [END forms_duplicate_form] |
0 commit comments