### Setup Documentation Build Environment Source: https://github.com/iterative/pydrive2/blob/main/docs/README.md Commands to install necessary tools like Sphinx and its theme, and to build the documentation site locally. This prepares the environment for generating the PyDrive2 documentation. ```bash pip install sphinx apt-get install python-sphinx pip install furo sphinx-build docs dist/site -b dirhtml -a ``` -------------------------------- ### Install PyDrive2 via pip Source: https://github.com/iterative/pydrive2/blob/main/README.rst Instructions on how to install PyDrive2 using the standard pip command. ```bash $ pip install PyDrive2 ``` -------------------------------- ### APIDOC: PyDrive2 File Listing Documentation Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst General documentation on how to easily list files and folders in Google Drive using PyDrive2, as referenced by 'File listing made easy'. This section provides guidance and examples for retrieving file and folder metadata. ```APIDOC Documentation Section: File listing made easy Description: Provides detailed instructions and examples for listing files and folders in Google Drive. Reference: /PyDrive2/filelist/ ``` -------------------------------- ### Install test dependencies for PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/pydrive2/test/README.rst This command installs the project in editable mode along with its 'tests' and 'fsspec' extra dependencies. This is necessary to run the PyDrive2 test suite. ```bash pip install -e .[tests,fsspec] ``` -------------------------------- ### Install PyDrive2 development version from GitHub Source: https://github.com/iterative/pydrive2/blob/main/README.rst Instructions on how to install the current development version of PyDrive2 directly from its GitHub repository. ```bash $ pip install git+https://github.com/iterative/PyDrive2.git#egg=PyDrive2 ``` -------------------------------- ### Setup Python virtual environment Source: https://github.com/iterative/pydrive2/blob/main/pydrive2/test/README.rst These commands create a new Python virtual environment named '.env' using the specified Python interpreter, and then activate it. This isolates project dependencies from the system-wide Python installation. ```bash virtualenv -p python .env source .env/bin/activate ``` -------------------------------- ### Install PyDrive2 with fsspec dependencies Source: https://github.com/iterative/pydrive2/blob/main/README.rst Instructions to install PyDrive2 along with the necessary dependencies for fsspec integration. ```bash $ pip install PyDrive2[fsspec] ``` -------------------------------- ### Deploy Documentation to GitHub Pages Source: https://github.com/iterative/pydrive2/blob/main/docs/README.md Commands to initialize a Git repository within the built documentation directory, commit the changes, and force-push them to the 'gh-pages' branch on GitHub, effectively updating the live documentation. ```bash cd dist/site git init git add . git commit -m "update pages" git branch -M gh-pages git push -f git@github.com:iterative/PyDrive2 gh-pages ``` -------------------------------- ### Install PyDrive2 development version from GitHub Source: https://github.com/iterative/pydrive2/blob/main/docs/index.rst This command installs the current development version of PyDrive2 directly from its GitHub repository, useful for accessing the latest features or bug fixes. ```bash $ pip install git+https://github.com/iterative/PyDrive2.git#egg=PyDrive2 ``` -------------------------------- ### Manage Google Drive files with PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/README.rst Examples of creating, uploading, updating, downloading, and changing file properties using PyDrive2's simplified file management methods. ```python file1 = drive.CreateFile({'title': 'Hello.txt'}) file1.SetContentString('Hello') file1.Upload() # Files.insert() file1['title'] = 'HelloWorld.txt' # Change title of the file file1.Upload() # Files.patch() content = file1.GetContentString() # 'Hello' file1.SetContentString(content+' World!') # 'Hello World!' file1.Upload() # Files.update() file2 = drive.CreateFile() file2.SetContentFile('hello.png') file2.Upload() print('Created file %s with mimeType %s' % (file2['title'], file2['mimeType'])) # Created file hello.png with mimeType image/png file3 = drive.CreateFile({'id': file2['id']}) print('Downloading file %s from Google Drive' % file3['title']) # 'hello.png' file3.GetContentFile('world.png') # Save Drive file as a local file # or download Google Docs files in an export format provided. # downloading a docs document as an html file: docsfile.GetContentFile('test.html', mimetype='text/html') ``` -------------------------------- ### Create and Update Files with PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This snippet shows how to create a new file on Google Drive using PyDrive2. It initializes a GoogleDrive instance, creates a GoogleDriveFile with a specified title, sets its content from a string, and then uploads it to Google Drive. This method simplifies file creation and content updates. ```python from pydrive2.drive import GoogleDrive drive = GoogleDrive(gauth) file1 = drive.CreateFile({'title': 'Hello.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'. file1.SetContentString('Hello World!') # Set content of the file from given string. file1.Upload() ``` -------------------------------- ### Copy settings files for local tests Source: https://github.com/iterative/pydrive2/blob/main/pydrive2/test/README.rst This command navigates to the test settings directory and copies all YAML configuration files into the 'local' subdirectory, preparing the environment for local test execution. ```bash cd pydrive2/test/settings && cp *.yaml local ``` -------------------------------- ### List Files in Google Drive Root Folder Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This code snippet retrieves a list of all files in the Google Drive root folder that are not trashed. It iterates through the results, which are handled by PyDrive2's pagination, and prints the title and ID of each file. This provides a simple way to browse files. ```python # Auto-iterate through all files that matches this query file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id'])) ``` -------------------------------- ### Install PyDrive2 stable version via pip Source: https://github.com/iterative/pydrive2/blob/main/docs/index.rst This command installs the latest stable release of PyDrive2 from PyPI using the pip package manager. ```bash $ pip install PyDrive2 ``` -------------------------------- ### Use GDriveFileSystem for fsspec integration Source: https://github.com/iterative/pydrive2/blob/main/README.rst Example of initializing and using GDriveFileSystem from PyDrive2 for fsspec-compatible file system operations on Google Drive. ```python from pydrive2.fs import GDriveFileSystem # replace `root` with ID of a drive or directory and give service account access to it fs = GDriveFileSystem("root", client_id=my_id, client_secret=my_secret) for root, dnames, fnames in fs.walk("root"): ... ``` -------------------------------- ### Python: Navigate and Create Google Drive Folders Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This Python snippet handles user input to navigate through Google Drive folders or create new ones. It returns the ID of the selected or newly created folder, ensuring local directory creation if a new folder is made. It relies on external functions like 'create_folder' and 'folder_browser', and global variables like 'HOME_DIRECTORY', 'ROOT_FOLDER_NAME', and 'USERNAME'. ```python inp=input() if inp=='/': return parent_id elif inp==':': print("Enter Name of Folder You Want to Create") inp=input() newfolder=create_folder(parent_id,inp) if not os.path.exists(HOME_DIRECTORY+ROOT_FOLDER_NAME+os.path.sep+USERNAME): os.makedirs(HOME_DIRECTORY+ROOT_FOLDER_NAME+os.path.sep+USERNAME) return newfolder['id'] else: folder_selected=inp for element in folder_list: if type(element) is dict: if element["title"]==folder_selected: struc=element["list"] browsed.append(folder_selected) print("Inside "+folder_selected) return folder_browser(struc,element['id']) ``` -------------------------------- ### Install PyDrive2 with fsspec support Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Installs the PyDrive2 library along with the necessary fsspec dependencies using pip, enabling Google Drive file system capabilities. ```sh pip install 'pydrive2[fsspec]' ``` -------------------------------- ### Sample PyDrive2 settings.yaml Configuration Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst An example `settings.yaml` file demonstrating how to configure PyDrive2 for client-based authentication, including client ID/secret, credential saving, refresh token retrieval, and specific OAuth scopes. ```yaml client_config_backend: settings client_config: client_id: 9637341109347.apps.googleusercontent.com client_secret: psDskOoWr1P602PXRTHi save_credentials: True save_credentials_backend: file save_credentials_file: credentials.json get_refresh_token: True oauth_scope: - https://www.googleapis.com/auth/drive.file - https://www.googleapis.com/auth/drive.install - https://www.googleapis.com/auth/drive.metadata ``` -------------------------------- ### Create a Subfolder in Google Drive Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This function demonstrates how to create a new subfolder within an existing parent folder on Google Drive. It sets the folder's title, specifies its parent, and assigns the correct MIME type for a Google Drive folder before uploading it. The function returns the newly created folder object. ```python def create_folder(parent_folder_id, subfolder_name): newFolder = drive.CreateFile({'title': subfolder_name, "parents": [{"kind": "drive#fileLink", "id": parent_folder_id}],"mimeType": "application/vnd.google-apps.folder"}) newFolder.Upload() return newFolder ``` -------------------------------- ### Retrieve File ID by Title in a Directory Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This function searches for a file's ID within a specified parent directory using its title. It iterates through the files in the given directory and returns the ID of the first file whose title matches the input. If no match is found, it returns None. ```python def get_id_of_title(title,parent_directory_id): foldered_list=drive.ListFile({'q': "'"+parent_directory_id+"' in parents and trashed=false"}).GetList() for file in foldered_list: if(file['title']==title): return file['id'] return None ``` -------------------------------- ### APIDOC: PyDrive2 GoogleDriveFile Class Reference Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst Reference to the `GoogleDriveFile` class within PyDrive2, which represents a file or folder in Google Drive. This class provides methods and properties for interacting with Google Drive items. ```APIDOC Class: GoogleDriveFile Description: Represents a file or folder object in Google Drive, providing an interface for operations like listing, downloading, and uploading. Reference: /PyDrive2/pydrive2/#pydrive2.files.GoogleDriveFile ``` -------------------------------- ### Querying Google Drive Files by Name and Type Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Shows how to retrieve a list of `GoogleDriveFile` instances using complex queries. This example filters files by title and MIME type to ensure uniqueness. ```python from pydrive2.drive import GoogleDrive # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) filename = 'file_test' # Query query = {'q': f"title = '{filename}' and mimeType='{mimetype}'"} # Get list of files that match against the query files = drive.ListFile(query).GetList() ``` -------------------------------- ### Browse Google Drive Folders and Print Titles Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This function iterates through a list of folder elements, printing their titles or the element itself if not a dictionary. It's designed to display contents of a directory, likely as part of an interactive folder browsing utility. The snippet appears incomplete, suggesting further user interaction. ```python browsed=[] def folder_browser(folder_list,parent_id): for element in folder_list: if type(element) is dict: print (element['title']) else: print (element) print("Enter Name of Folder You Want to Use\nEnter '/' to use current folder\nEnter ':' to create New Folder and") ``` -------------------------------- ### Authenticate PyDrive2 with Google Drive API Source: https://github.com/iterative/pydrive2/blob/main/docs/quickstart.rst This code snippet demonstrates how to authenticate PyDrive2 with the Google Drive API using a local web server. It automatically handles the OAuth2.0 flow, prompting the user for authentication in a web browser. Ensure 'client_secrets.json' is in the working directory. ```python from pydrive2.auth import GoogleAuth gauth = GoogleAuth() gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. ``` -------------------------------- ### Run Pytest tests Source: https://github.com/iterative/pydrive2/blob/main/pydrive2/test/README.rst This command executes the Pytest test suite with verbose output (-v) and disables capturing of stdout/stderr (-s), allowing for detailed test results to be displayed directly. ```bash py.test -v -s ``` -------------------------------- ### List all files matching a query using PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/docs/filelist.rst This snippet demonstrates how to retrieve all files matching a specific query using PyDrive2. It initializes a GoogleDrive instance with an authenticated GoogleAuth instance and then uses `ListFile` with a query to get a list of files, iterating through them to print their titles and IDs. The query syntax follows Google Drive API specifications for searching files. ```python from pydrive2.drive import GoogleDrive drive = GoogleDrive(gauth) # Create GoogleDrive instance with authenticated GoogleAuth instance # Auto-iterate through all files in the root folder. file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id'])) ``` -------------------------------- ### Fetch Special Metadata for Google Drive Files Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet illustrates how to retrieve specific or all metadata fields for a Google Drive file using FetchMetadata(). It shows examples of fetching basic metadata, all available metadata, or a comma-separated list of specific fields like 'permissions' or 'labels,mimeType'. This function provides access to metadata not directly settable via dictionary-like access. ```python file1 = drive.CreateFile({'id': ''}) # Fetches all basic metadata fields, including file size, last modified etc. file1.FetchMetadata() # Fetches all metadata available. file1.FetchMetadata(fetch_all=True) # Fetches the 'permissions' metadata field. file1.FetchMetadata(fields='permissions') # You can update a list of specific fields like this: file1.FetchMetadata(fields='permissions,labels,mimeType') ``` -------------------------------- ### Paginate and iterate through files with PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/docs/filelist.rst This example shows how to paginate and iterate through a large list of files using PyDrive2. It sets `maxResults` to retrieve files in batches (e.g., 10 at a time) and then iterates through these batches, printing the number of files received in each batch and then details of individual files. This is useful for handling large datasets efficiently. ```python # Paginate file lists by specifying number of max results for file_list in drive.ListFile({'q': 'trashed=true', 'maxResults': 10}): print('Received %s files from Files.list()' % len(file_list)) # <= 10 for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id'])) ``` -------------------------------- ### PyDrive2: Custom Authentication Configuration via settings.yaml Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst This section outlines the structure and available fields for the `settings.yaml` file, which allows for custom authentication flows in PyDrive2, particularly useful for silent or remote machine setups. It details various configuration options for client secrets, service accounts, credential saving, and OAuth scopes, enabling fine-grained control over the authentication process. ```APIDOC client_config_backend: {{str}} client_config_file: {{str}} client_config: client_id: {{str}} client_secret: {{str}} auth_uri: {{str}} token_uri: {{str}} redirect_uri: {{str}} revoke_uri: {{str}} service_config: client_user_email: {{str}} client_json_file_path: {{str}} client_json_dict: {{dict}} client_json: {{str}} save_credentials: {{bool}} save_credentials_backend: {{str}} save_credentials_file: {{str}} save_credentials_dict: {{dict}} save_credentials_key: {{str}} get_refresh_token: {{bool}} oauth_scope: {{list of str}} Fields explained: client_config_backend (str): From where to read client configuration(API application settings such as client_id and client_secrets) from. Valid values are 'file', 'settings' and 'service'. Default: 'file'. Required: No. client_config_file (str): When client_config_backend is 'file', path to the file containing client configuration. Default: 'client_secrets.json'. Required: No. client_config (dict): Place holding dictionary for client configuration when client_config_backend is 'settings'. Required: Yes, only if client_config_backend is 'settings' and not using service_config client_config['client_id'] (str): Client ID of the application. Required: Yes, only if client_config_backend is 'settings' client_config['client_secret'] (str): Client secret of the application. Required: Yes, only if client_config_backend is 'settings' client_config['auth_uri'] (str): The authorization server endpoint URI. Default: 'https://accounts.google.com/o/oauth2/auth'. Required: No. client_config['token_uri'] (str): The token server endpoint URI. Default: 'https://accounts.google.com/o/oauth2/token'. Required: No. client_config['redirect_uri'] (str): Redirection endpoint URI. Default: 'urn:ietf:wg:oauth:2.0:oob'. Required: No. client_config['revoke_uri'] (str): Revoke endpoint URI. Default: None. Required: No. service_config (dict): Place holding dictionary for client configuration when client_config_backend is 'service' or 'settings' and using service account. Required: Yes, only if client_config_backend is 'service' or 'settings' and not using client_config service_config['client_user_email'] (str): User email that authority was delegated_ to. Required: No. ``` -------------------------------- ### PyDrive2 GoogleDrive.CreateFile Method Reference Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Reference for the 'CreateFile' method of the 'GoogleDrive' class, used to create a new 'GoogleDriveFile' instance, optionally with initial metadata. ```APIDOC GoogleDrive.CreateFile(metadata: dict = None): Creates a new GoogleDriveFile instance. metadata: (Optional) A dictionary containing initial metadata for the file (e.g., 'title', 'mimeType', 'parents'). Returns: A GoogleDriveFile instance. ``` -------------------------------- ### API Documentation for pydrive2.settings module Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `pydrive2.settings` module, responsible for managing configuration settings for the PyDrive2 library. It exposes all public and undocumented members, along with their inheritance hierarchy. ```APIDOC Module: pydrive2.settings Description: Manages configuration settings. Members: All public and undocumented members. Inheritance: Shown. ``` -------------------------------- ### API Documentation for pydrive2.fs.GDriveFileSystem class Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `GDriveFileSystem` class within the `pydrive2.fs` module, which provides a file system-like interface for interacting with Google Drive. It shows the class's inheritance hierarchy. ```APIDOC Class: pydrive2.fs.GDriveFileSystem Description: Provides a file system interface for Google Drive. Inheritance: Shown. ``` -------------------------------- ### Initialize GDriveFileSystem for local webserver authentication Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Demonstrates how to initialize GDriveFileSystem for local webserver authentication using a client ID and secret. This method typically requires interactive authentication on first use. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( "root", client_id="my_client_id", client_secret="my_client_secret", ) ``` -------------------------------- ### Fetching File Permissions with PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Demonstrates how to retrieve file permissions using `GetPermissions()` and by fetching metadata with `FetchMetadata(fields='permissions')`. Permissions are accessible as a list or via `file1['permissions']`. ```python file1 = drive.CreateFile() # Fetch permissions. permissions = file1.GetPermissions() print(permissions) # The permissions are also available as file1['permissions']: print(file1['permissions']) ``` ```python # Fetch Metadata, including the permissions field. file1.FetchMetadata(fields='permissions') # The permissions array is now available for further use. print(file1['permissions']) ``` -------------------------------- ### API Documentation for pydrive2.auth module Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `pydrive2.auth` module, which handles authentication processes for the PyDrive2 library. It exposes all public and undocumented members, along with their inheritance hierarchy. ```APIDOC Module: pydrive2.auth Description: Handles authentication processes. Members: All public and undocumented members. Inheritance: Shown. ``` -------------------------------- ### Upload Image File with Metadata (PyDrive2) Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Demonstrates how to define metadata for an image file, create a new file instance with it, and upload the file to Google Drive using PyDrive2. This snippet assumes 'drive' is an initialized GoogleDrive instance and 'metadata' is a dictionary. ```python 'parents': [ {"id": id_drive_folder} ], 'title': 'image_test', 'mimeType': 'image/jpeg' } # Create file file = drive.CreateFile(metadata=metadata) file.Upload() ``` -------------------------------- ### Uploading and Updating File Content Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Illustrates how to manage file content using `SetContentFile()` for local files and `SetContentString()` for string content. It also shows how to update existing file content and retrieve content with a specific character encoding using `GetContentString()`. ```python file4 = drive.CreateFile({'title':'appdata.json', 'mimeType':'application/json'}) file4.SetContentString('{"firstname": "John", "lastname": "Smith"}') file4.Upload() # Upload file. file4.SetContentString('{"firstname": "Claudio", "lastname": "Afshar"}') file4.Upload() # Update content of the file. ``` ```python file5 = drive.CreateFile() # Read file and set it as a content of this instance. file5.SetContentFile('cat.png') file5.Upload() # Upload the file. print('title: %s, mimeType: %s' % (file5['title'], file5['mimeType'])) # title: cat.png, mimeType: image/png ``` ```python content_string = file4.GetContentString(encoding='ISO-8859-1') ``` -------------------------------- ### API Documentation for pydrive2.drive module Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `pydrive2.drive` module, providing core functionalities for interacting with Google Drive within the PyDrive2 library. It exposes all public and undocumented members, along with their inheritance hierarchy. ```APIDOC Module: pydrive2.drive Description: Provides core Google Drive functionalities. Members: All public and undocumented members. Inheritance: Shown. ``` -------------------------------- ### Walk a GDriveFileSystem directory Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Demonstrates how to traverse a Google Drive directory using the `walk` method of the `GDriveFileSystem` instance, printing out directories and files found. Replace 'root' with the actual ID of a drive or directory. ```python # replace `root` with ID of a drive or directory and give service account access to it for root, dnames, fnames in fs.walk("root"): for dname in dnames: print(f"dir: {root}/{dname}") for fname in fnames: print(f"file: {root}/{fname}") ``` -------------------------------- ### Initialize GDriveFileSystem using client JSON string Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Initializes GDriveFileSystem by providing client credentials directly as a JSON string. This is useful for dynamic credential loading without requiring file access. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( "root", client_id="my_client_id", client_secret="my_client_secret", client_json=json_string, ) ``` -------------------------------- ### Initialize GDriveFileSystem with service account from keyfile string Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Initializes GDriveFileSystem using a service account by providing the JSON key directly as a string. This is suitable for environments where file access is restricted or credentials are dynamically managed. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( # replace with ID of a drive or directory and give service account access to it "root", use_service_account=True, client_json=json_string, ) ``` -------------------------------- ### Paginate Google Drive file listings with PyDrive2 Source: https://github.com/iterative/pydrive2/blob/main/README.rst Demonstrates how PyDrive2 automatically handles pagination for file listings, allowing iteration through all matching files or fetching files in batches. ```python # Auto-iterate through all files that matches this query file_list = drive.ListFile({'q': "'root' in parents"}).GetList() for file1 in file_list: print('title: {}, id: {}'.format(file1['title'], file1['id'])) # Paginate file lists by specifying number of max results for file_list in drive.ListFile({'maxResults': 10}): print('Received {} files from Files.list()'.format(len(file_list))) # <= 10 for file1 in file_list: print('title: {}, id: {}'.format(file1['title'], file1['id'])) ``` -------------------------------- ### Manage Google Drive Files: Delete, Trash, and Un-Trash Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet illustrates how to manage the lifecycle of a Google Drive file by moving it to trash, restoring it from trash, and permanently deleting it. It first uploads a file, then demonstrates the Trash(), UnTrash(), and Delete() methods on a GoogleDriveFile object. Note that Delete() is permanent, while Trash() allows recovery. ```python # Create GoogleDriveFile instance and upload it. file1 = drive.CreateFile() file1.Upload() file1.Trash() # Move file to trash. file1.UnTrash() # Move file out of trash. file1.Delete() # Permanently delete the file. ``` -------------------------------- ### PyDrive2 GoogleDriveFile Class Reference Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Reference for the 'GoogleDriveFile' class in PyDrive2, detailing its methods for content manipulation, including uploading, downloading, and setting/getting content as strings or files. It also covers parameters for handling BOM and abusive files. ```APIDOC GoogleDriveFile: Upload(): Uploads the file content to Google Drive. GetContentFile(filename: str, remove_bom: bool = False, acknowledge_abuse: bool = False): Downloads file content to a local file. filename: The path to save the downloaded file. remove_bom: (Optional) If True, removes Byte Order Marks from the beginning of the file. acknowledge_abuse: (Optional) If True, acknowledges the risks of downloading potential malware or spam. GetContentString(remove_bom: bool = False, acknowledge_abuse: bool = False): Downloads file content as a string. remove_bom: (Optional) If True, removes Byte Order Marks from the beginning of the string. acknowledge_abuse: (Optional) If True, acknowledges the risks of downloading potential malware or spam. SetContentFile(filename: str): Sets the file content from a local file. filename: The path to the local file whose content will be set. SetContentString(content: str): Sets the file content from a string. content: The string content to set for the file. ``` -------------------------------- ### Initialize GDriveFileSystem with service account from keyfile path Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Configures GDriveFileSystem to authenticate using a service account specified by a JSON keyfile path. The service account must have appropriate access to the target Google Drive or directory. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( # replace with ID of a drive or directory and give service account access to it "root", use_service_account=True, client_json_file_path="/path/to/keyfile.json", ) ``` -------------------------------- ### GDriveFileSystem Additional Parameters Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Describes additional configuration parameters for the GDriveFileSystem constructor, including options for moving files to trash instead of deleting and acknowledging abusive files. ```APIDOC GDriveFileSystem Parameters: trash_only (bool): Move files to trash instead of deleting. acknowledge_abuse (bool): Acknowledging the risk and download file identified as abusive. ``` -------------------------------- ### Listing File Revisions Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Demonstrates how to fetch revisions for a `GoogleDriveFile` using the `GetRevisions()` method. Note that not all file objects have revisions, and calling this on a file without revisions will raise an exception. ```python # Create a new file file1 = drive.CreateFile() # Fetch revisions. revisions = file1.GetRevisions() print(revisions) ``` -------------------------------- ### API Documentation for pydrive2.files module Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `pydrive2.files` module, which manages file-related operations within the PyDrive2 library. It exposes all public and undocumented members, along with their inheritance hierarchy. ```APIDOC Module: pydrive2.files Description: Manages file-related operations. Members: All public and undocumented members. Inheritance: Shown. ``` -------------------------------- ### Initialize GDriveFileSystem with profile for multiple users Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Initializes GDriveFileSystem using a client ID, secret, and a unique profile name. This helps avoid credential conflicts when managing multiple user accounts or different authentication contexts. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( "root", client_id="my_client_id", client_secret="my_client_secret", profile="myprofile", ) ``` -------------------------------- ### List Permissions for Google Drive Files Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet explains how to retrieve existing permissions for a Google Drive file. It demonstrates using the GetPermissions() function of a GoogleDriveFile object to fetch and inspect the permissions associated with the file. ```python # Create a new file (or use an existing one) file1 = drive.CreateFile() file1.Upload() permissions = file1.GetPermissions() for p in permissions: print(f"Type: {p['type']}, Role: {p['role']}") ``` -------------------------------- ### Initialize GDriveFileSystem using client JSON file path Source: https://github.com/iterative/pydrive2/blob/main/docs/fsspec.rst Configures GDriveFileSystem to use credentials from a specified JSON keyfile path. This method avoids interactive authentication if credentials are pre-cached or provided in the file. ```python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( "root", client_id="my_client_id", client_secret="my_client_secret", client_json_file_path="/path/to/keyfile.json", ) ``` -------------------------------- ### PyDrive2 GoogleAuth Class Reference Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Reference for the 'GoogleAuth' class in PyDrive2, which handles authentication processes for interacting with the Google Drive API. ```APIDOC GoogleAuth: Class responsible for handling authentication with the Google Drive API. ``` -------------------------------- ### Download File by ID to Local File (PyDrive2) Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Illustrates how to download a file from Google Drive to a local file path using its ID. It initializes a GoogleDriveFile instance and uses 'GetContentFile()' to save the content. ```python # Initialize GoogleDriveFile instance with file id. file6 = drive.CreateFile({'id': file5['id']}) file6.GetContentFile('catlove.png') # Download file as 'catlove.png'. ``` -------------------------------- ### Implement Custom PyDrive2 OAuth Authentication Flow Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst Demonstrates how to build a customized authentication flow using PyDrive2, involving obtaining an authentication URL, prompting the user for authorization, and then using the retrieved code to authorize the application. ```python from pydrive2.auth import GoogleAuth gauth = GoogleAuth() auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit code = AskUserToVisitLinkAndGiveCode(auth_url) # Your customized authentication flow gauth.Auth(code) # Authorize and build service from the code ``` -------------------------------- ### API Documentation for pydrive2.apiattr module Source: https://github.com/iterative/pydrive2/blob/main/docs/pydrive2.rst Documents the `pydrive2.apiattr` module, which is responsible for managing API attributes within the PyDrive2 library. It exposes all public and undocumented members, along with their inheritance hierarchy. ```APIDOC Module: pydrive2.apiattr Description: Manages API attributes. Members: All public and undocumented members. Inheritance: Shown. ``` -------------------------------- ### PyDrive2 Authentication Configuration Parameters Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst Detailed description of configuration parameters available for PyDrive2 authentication, including service account paths, credential saving options, and OAuth scope settings. These parameters can be used when initializing GoogleAuth. ```APIDOC service_config['client_json_file_path'] (str): Path to service account `.json` key file. Required: No. service_config['client_json_dict'] (dict): Service account `.json` key file loaded into a dictionary. Required: No. service_config['client_json'] (str): Service account `.json` key file loaded into a string. Required: No. save_credentials (bool): True if you want to save credentials. Default: False. Required: No. save_credentials_backend (str): Backend to save credentials to. 'file' and 'dictionary' are the only valid values for now. Default: 'file'. Required: No. save_credentials_file (str): Destination of credentials file. Required: Yes, only if save_credentials_backend is 'file'. save_credentials_dict (dict): Dict to use for storing credentials. Required: Yes, only if save_credentials_backend is 'dictionary'. save_credentials_key (str): Key within the save_credentials_dict to store the credentials in. Required: Yes, only if save_credentials_backend is 'dictionary'. get_refresh_token (bool): True if you want to retrieve refresh token along with access token. Default: False. Required: No. oauth_scope (list of str): OAuth scope to authenticate. Default: ['https://www.googleapis.com/auth/drive']. Required: No. ``` -------------------------------- ### Download, Modify, and Re-upload File Content (PyDrive2) Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Shows how to download file content as a string, modify it (e.g., replace text), and then re-upload the modified content back to Google Drive. This uses 'GetContentString()' and 'SetContentString()'. ```python # Initialize GoogleDriveFile instance with file id. file7 = drive.CreateFile({'id': file4['id']}) content = file7.GetContentString() # content: '{"firstname": "Claudio", "lastname": "Afshar"}' file7.SetContentString(content.replace('lastname', 'familyname')) file7.Upload() # Uploaded content: '{"firstname": "Claudio", "familyname": "Afshar"}' ``` -------------------------------- ### Insert Permissions for Google Drive Files Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet demonstrates how to insert new permissions for a Google Drive file, making it publicly readable via a link. It creates a file, then uses InsertPermission() to add a permission with 'type': 'anyone', 'value': 'anyone', and 'role': 'reader'. The sharable link is then displayed. Note that InsertPermission() automatically calls GetPermissions() afterwards. ```python file1 = drive.CreateFile() file1.Upload() # Insert the permission. permission = file1.InsertPermission({ 'type': 'anyone', 'value': 'anyone', 'role': 'reader'}) print(file1['alternateLink']) # Display the sharable link. ``` -------------------------------- ### Authenticate with Google Drive using PyDrive2 OAuth Source: https://github.com/iterative/pydrive2/blob/main/README.rst Demonstrates how to perform OAuth2.0 authentication with Google Drive using PyDrive2, requiring a client_secrets.json file. ```python from pydrive2.auth import GoogleAuth from pydrive2.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) ``` -------------------------------- ### PyDrive2: Basic OAuth2.0 Authentication with GoogleAuth Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst This snippet demonstrates how to perform basic OAuth2.0 authentication using PyDrive2's GoogleAuth class. It shows two methods: LocalWebserverAuth for automatic browser-based authentication and CommandLineAuth for manual token input, simplifying the complex OAuth process into just two lines. ```python from pydrive2.auth import GoogleAuth gauth = GoogleAuth() # Create local webserver and auto handles authentication. gauth.LocalWebserverAuth() # Or use the CommandLineAuth(), which provides you with a link to paste # into your browser. The site it leads to then provides you with an # authentication token which you paste into the command line. # Commented out as it is an alternative to the LocalWebserverAuth() above, # and someone will just copy-paste the entire thing into their editor. # gauth.CommandLineAuth() ``` -------------------------------- ### Upload a New File to Google Drive Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet demonstrates how to upload a new file to Google Drive using PyDrive2. It initializes a GoogleDrive instance with an authenticated GoogleAuth object, creates a GoogleDriveFile instance with a specified title, and then uploads the file. The file's title and ID are printed upon successful upload. ```python from pydrive2.drive import GoogleDrive # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) # Create GoogleDriveFile instance with title 'Hello.txt'. file1 = drive.CreateFile({'title': 'Hello.txt'}) file1.Upload() # Upload the file. print('title: %s, id: %s' % (file1['title'], file1['id'])) # title: Hello.txt, id: {{FILE_ID}} ``` -------------------------------- ### Uploading In-Memory Byte Data Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Demonstrates how to upload file content directly from an in-memory bytes buffer using Python's `io.BytesIO` module. This is useful for uploading data like base64 decoded images without saving them to a file. ```python import io from pydrive2.drive import GoogleDrive # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) # Define file name and type metadata = { 'title': 'image_test', 'mimeType': 'image/jpeg' } # Create file file = drive.CreateFile(metadata=metadata) # Buffered I/O implementation using an in-memory bytes buffer. image_file = io.BytesIO(image_bytes) # Set the content of the file file.content = image_file # Upload the file to google drive file.Upload() ``` -------------------------------- ### Update Google Drive File Metadata Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet shows how to modify the metadata of an existing Google Drive file. It demonstrates changing the file's title by treating the GoogleDriveFile object as a dictionary and then calling Upload() to persist the changes. The updated title is then printed. ```python file1['title'] = 'HelloWorld.txt' # Change title of the file. file1.Upload() # Update metadata. print('title: %s' % file1['title']) # title: HelloWorld.txt. ``` -------------------------------- ### Retrieve Google Drive File Metadata by ID Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst This snippet demonstrates how to fetch file metadata using only its ID. It initializes a GoogleDriveFile instance with a known file ID and then accesses its metadata fields, such as title and MIME type, directly from the object, similar to accessing a dictionary. ```python # Create GoogleDriveFile instance with file id of file1. file2 = drive.CreateFile({'id': file1['id']}) print('title: %s, mimeType: %s' % (file2['title'], file2['mimeType'])) # title: HelloWorld.txt, mimeType: text/plain ``` -------------------------------- ### Removing a Specific File Permission Source: https://github.com/iterative/pydrive2/blob/main/docs/filemanagement.rst Illustrates how to remove a specific permission from a Google Drive file using `DeletePermission(permission_id)`. Requires the file ID and the permission ID to be deleted. ```python file1 = drive.CreateFile({'id': ''}) permissions = file1.GetPermissions() # Download file permissions. permission_id = permissions[1]['id'] # Get a permission ID. file1.DeletePermission(permission_id) # Delete the permission. ``` -------------------------------- ### Authenticate PyDrive2 with a Service Account Source: https://github.com/iterative/pydrive2/blob/main/docs/oauth.rst Provides a Python function to authenticate PyDrive2 using a Google service account. This method offers automatic login and is suitable for non-human interactions, requiring the service account email to be shared with relevant Google Drive resources. ```python from pydrive2.auth import GoogleAuth from pydrive2.drive import GoogleDrive 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": "service-secrets.json", } } # Create instance of GoogleAuth gauth = GoogleAuth(settings=settings) # Authenticate gauth.ServiceAuth() return gauth ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.