diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 4a308825..de41641e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -10,6 +10,9 @@ jobs: steps: - uses: actions/checkout@v7 + with: + # setuptools-scm uses release tags to version the installed package. + fetch-depth: 0 - uses: actions/setup-python@v7 with: diff --git a/CHANGES b/CHANGES index 4d2251b3..2cec5ad7 100644 --- a/CHANGES +++ b/CHANGES @@ -1 +1,3 @@ +For release notes, see https://github.com/iterative/PyDrive2/releases. + v1.0.0, Aug 16, 2013 -- Initial release. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 5a39c51e..788a4281 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -1,26 +1,24 @@ Contributing guidelines ======================= -How to become a contributor and submit your own code ----------------------------------------------------- - -TODO - Contributing code -~~~~~~~~~~~~~~~~~ +----------------- -If you have improvements to PyDrive2, send us your pull requests! For those -just getting started, Github has a `howto`_. +Submit changes in a pull request. GitHub's `pull request guide`_ describes +how to propose and review changes. Install the development tools with ``python -m pip install -e '.[tests,fsspec,typing]'``. Run ``ruff check .`` to lint Python files and ``ruff format .`` to format them. Run ``python -m mypy`` to type-check the package for Python 3.11. -.. _howto: https://help.github.com/articles/using-pull-requests/ +See the `test guide `_ for offline and live suites +and the `documentation guide `_ to preview the site. + +.. _pull request guide: https://docs.github.com/en/pull-requests Live Drive tests for external pull requests -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +------------------------------------------- Fork and Dependabot PRs run offline tests automatically. A repository maintainer or admin can comment ``/test-drive`` to request live tests. diff --git a/docs/README.md b/docs/README.md index 86b5d3b0..da6c8a1b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,27 +1,19 @@ -This document outlines how to rebuild the documentation. +# Building the PyDrive2 documentation -## Setup +From the repository root, install the package with fsspec support and the +documentation dependencies. Sphinx imports the installed package to generate +the API reference. -- Install Sphinx: `pip install sphinx` or `apt-get install python-sphinx` -- Install theme: `pip install furo` -- Build site: `sphinx-build docs dist/site -b dirhtml -a` - -Updating GitHub Pages: - -```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 +```sh +python -m pip install -e '.[fsspec]' -r docs/requirements.txt +python -m sphinx -W --keep-going -b dirhtml docs dist/site +python -m http.server --directory dist/site 8000 ``` -## Contributing - -If code files were added, the easiest way to reflect code changes in the -documentation by referencing the file from within `pydrive.rst`. +Open to preview the site. To check external links, +run `python -m sphinx -b linkcheck docs dist/linkcheck`. -If a non-code related file was added (it has to have the `.rst` ending), -then add the file name to the list of names under "Table of Contents" -in `index.rst`. Make sure to add the file name excluding the `.rst` file ending. +Add new guides to the table of contents in `docs/index.rst`. Public modules +and classes are documented in `docs/pydrive2.rst`. The **Build docs** +workflow builds pull requests and publishes successful builds from `main` +to GitHub Pages. diff --git a/docs/conf.py b/docs/conf.py index 64112a5b..a4747c5e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -13,6 +13,7 @@ import os import sys +from importlib.metadata import version as package_version # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -22,9 +23,6 @@ exclude_dirnames = ["test"] # -- General configuration ------------------------------------------------ -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.8" - # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. @@ -56,10 +54,9 @@ # |version| and |release|, also used in various other places throughout the # built documents. # -# The short X.Y version. -version = "1.19.0" -# The full version, including alpha/beta/rc tags. -release = "1.19.0" +release = package_version("PyDrive2") +version = ".".join(release.split(".")[:2]) +html_title = f"{project} documentation" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -279,7 +276,7 @@ "PyDrive2 Documentation", author, "PyDrive2", - "One line description of project.", + "Python client and fsspec filesystem for Google Drive.", "Miscellaneous", ) ] diff --git a/docs/filelist.rst b/docs/filelist.rst index e9b7f468..8c751428 100644 --- a/docs/filelist.rst +++ b/docs/filelist.rst @@ -4,8 +4,10 @@ File listing made easy PyDrive2 handles pagination and returns :class:`~pydrive2.files.GoogleDriveFile` instances. -Get all files which matches the query -------------------------------------- +.. _get-all-files-which-matches-the-query: + +List matching files +------------------- Pass the `files.list query parameters`_ to :meth:`~pydrive2.drive.GoogleDrive.ListFile` as a dictionary. It returns a @@ -44,8 +46,7 @@ contains up to ten files. .. code-block:: python - # Paginate file lists by specifying number of max results - for file_list in drive.ListFile({'q': 'trashed=true', 'pageSize': 10}): + for file_list in drive.ListFile({'q': 'trashed=false', 'pageSize': 10}): print('Received %s files from Files.list()' % len(file_list)) # <= 10 for file1 in file_list: print('name: %s, id: %s' % (file1['name'], file1['id'])) diff --git a/docs/filemanagement.rst b/docs/filemanagement.rst index 3ed2a5c1..cdb2fd73 100644 --- a/docs/filemanagement.rst +++ b/docs/filemanagement.rst @@ -1,8 +1,6 @@ File management made easy ========================= -There are many methods to create and update file metadata and contents. With -*PyDrive*, you don't have to care about any of these different API methods. Edit the metadata or contents of a :class:`~pydrive2.files.GoogleDriveFile` and call :meth:`~pydrive2.files.GoogleDriveFile.Upload` to save the changes. @@ -21,7 +19,8 @@ In this example, ``gauth`` is an authenticated # Create GoogleDriveFile instance with name 'Hello.txt'. file1 = drive.CreateFile({'name': 'Hello.txt'}) - file1.Upload() # Upload the file. + file1.SetContentString('Hello') + file1.Upload() # Create a text file. print('name: %s, id: %s' % (file1['name'], file1['id'])) # name: Hello.txt, id: {{FILE_ID}} @@ -33,21 +32,17 @@ Google Drive. Delete, Trash and un-Trash files -------------------------------- -You may want to delete, trash, or un-trash a file. To do this use ``Delete()``, -``Trash()`` or ``UnTrash()`` on a GoogleDriveFile object. - -*Note:* ``Trash()`` *moves a file into the trash and can be recovered,* -``Delete()`` *deletes the file permanently and immediately.* +Use ``Trash()`` to move a file to the trash and ``UnTrash()`` to restore it. +``Delete()`` permanently deletes the file. This example creates a separate +file so you can continue working with ``Hello.txt`` in the following sections. .. code-block:: 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. + temporary = drive.CreateFile({"name": "temporary.txt"}) + temporary.Upload() + temporary.Trash() + temporary.UnTrash() + temporary.Delete() Update file metadata -------------------- @@ -85,97 +80,56 @@ Sample code continues from above: Handling special metadata ------------------------- -Not all metadata can be set with the methods described above. -PyDrive gives you access to the metadata of an object through -``file_object.FetchMetadata()``. This function has two optional parameters: -``fields`` and ``fetch_all``. +Drive returns a subset of file fields by default. Request specific fields +with a field mask or use ``fetch_all=True`` to request all available fields. .. code-block:: 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) + file2.FetchMetadata(fields="id,name,owners,capabilities") + file2.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,trashed,mimeType') - -See the `Drive API v3 file resource`_ for the available fields. +See the `Drive API v3 file resource`_ for available fields. Insert permissions __________________ -Insert, retrieving or deleting permissions is illustrated by making a file -readable to all who have a link to the file. +To share a file by link, create an ``anyone`` permission with the +``reader`` role. The file's sharing policy must allow link sharing. +Keep the returned permission ID if you want to revoke that grant later. .. code-block:: python - file1 = drive.CreateFile() - file1.Upload() - - # Insert the permission. - permission = file1.InsertPermission({ - 'type': 'anyone', - 'allowFileDiscovery': False, - 'role': 'reader'}) - - print(file1['webViewLink']) # Display the sharable link. - -Note: ``InsertPermission()`` calls ``GetPermissions()`` after successfully -inserting the permission. + shared = drive.CreateFile({"name": "Shared note.txt"}) + shared.Upload() + permission = shared.InsertPermission({ + "type": "anyone", + "allowFileDiscovery": False, + "role": "reader", + }) + print(shared["webViewLink"]) -See the `permissions.create request body`_ for the permission format. -This file is now shared and anyone with the link can view it. But what if you -want to check whether a file is already shared? +See the `permissions.create request body`_ for other permission types. List permissions ________________ -Permissions can be fetched using the ``GetPermissions()`` function of a -``GoogleDriveFile``, and can be used like so: - -.. code-block:: python - - # Create a new file - file1 = drive.CreateFile() - # Fetch permissions. - permissions = file1.GetPermissions() - print(permissions) - - # The permissions are also available as file1['permissions']: - print(file1['permissions']) - -For the more advanced user: ``GetPermissions()`` is a shorthand for: +Call ``GetPermissions()`` on an uploaded file or one opened by ID. +PyDrive2 follows the permission list's page tokens and stores the results +in the file object's ``permissions`` field. .. code-block:: python - # Fetch Metadata, including the permissions field. - file1.FetchMetadata(fields='permissions') - - # The permissions array is now available for further use. - print(file1['permissions']) + for grant in shared.GetPermissions(): + print(grant["id"], grant["role"]) Remove a Permission ___________________ -*PyDrive* allows you to remove a specific permission using the -``DeletePermission(permission_id)`` function. This function allows you to -delete one permission at a time by providing the permission's ID. +Revoke the grant created above using the ID returned by ``InsertPermission()``. .. code-block:: 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. + shared.DeletePermission(permission["id"]) Get files by complex queries ---------------------------- @@ -199,53 +153,32 @@ field such as ``mimeType`` in a Drive v3 search. See the List revisions ______________ -Revisions can be fetched using the ``GetRevisions()`` function of a -``GoogleDriveFile``, and can be used like so: +Use ``GetRevisions()`` on a file that has been uploaded or opened by ID. .. code-block:: python - # Create a new file - file1 = drive.CreateFile() - # Fetch revisions. revisions = file1.GetRevisions() - print(revisions) - -Not all files objects have revisions. If GetRevisions is called on a -file object that does not have revisions, an exception will be raised. - -Upgrading from Drive API v2 ---------------------------- - -PyDrive2 uses Drive API v3 for all requests. Existing file and folder IDs -remain valid. Use v3 names in metadata dictionaries, field masks, and queries: - -- ``title`` becomes ``name``, ``fileSize`` becomes ``size``, and - ``alternateLink`` becomes ``webViewLink``. -- File reads and listings request a subset of metadata by default. To read - additional fields, use ``FetchMetadata(fields="owners,capabilities")``, - ``FetchMetadata(fetch_all=True)``, or a list selector such as - ``files(id,name,shortcutDetails)``. -- Read ``trashed`` directly and supply parent IDs as strings, - for example ``{"parents": [folder_id]}``. Assign the new parent list and - call ``Upload()`` to move an existing file. -- Replace ``maxResults`` with ``pageSize`` and use a list field mask such - as ``files(id,name)``. See :doc:`filelist` for automatic pagination. -- For user or group permissions, use ``emailAddress`` in place of - ``value``. For link sharing, set ``allowFileDiscovery=False``. - When calling ``InsertPermission(permission, param=...)``, rename the v2 - request parameter ``sendNotificationEmails`` to ``sendNotificationEmail``. - For example, ``param={"sendNotificationEmail": False}`` disables the - notification when sharing with a user or group. -- To import a file, replace the v2 ``convert`` flag with the target - Workspace MIME type and pass the original media type to ``Upload()``. + for revision in revisions: + print(revision["id"]) + +.. _upgrading-from-drive-api-v2: + +Import a file into Google Workspace +----------------------------------- + +To import a CSV as a Google Sheet, set the destination MIME type on the +file and pass the source MIME type to ``Upload()``. .. code-block:: python - sheet = drive.CreateFile({"name": "Sales", "mimeType": "application/vnd.google-apps.spreadsheet"}) + sheet = drive.CreateFile({ + "name": "Sales", + "mimeType": "application/vnd.google-apps.spreadsheet", + }) sheet.SetContentFile("sales.csv") sheet.Upload(media_mime_type="text/csv") -See Google's `Drive v2 to v3 reference`_ for the full field and method-parameter mappings. +For changes to fields and request parameters, see :doc:`upgrading`. Upload and update file content ------------------------------ @@ -294,51 +227,29 @@ like so: Upload data as bytes in memory buffer ------------------------------------- -Data can be kept as bytes in an in-memory buffer when we use the ``io`` -module’s Byte IO operations, we can upload files that reside in memory, for -example we have a base64 image, we can decode the string and upload it to drive -without first saving it to disk and calling -:meth:`~pydrive2.files.GoogleDriveFile.SetContentFile`. +Assign a seekable binary stream to ``content``. The caller owns this +stream and can close it after the upload. .. code-block:: python - import io - from pydrive2.drive import GoogleDrive + from io import BytesIO - # Create GoogleDrive instance with authenticated GoogleAuth instance. - drive = GoogleDrive(gauth) - # Define file name and type - metadata = { - 'name': '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() + sample = drive.CreateFile({"name": "sample.bin"}) + with BytesIO(b"sample data") as stream: + sample.content = stream + sample.Upload() Upload file to a specific folder -------------------------------- -In order to upload a file into a specific drive folder we need to pass the -``id`` of the folder in the metadata passed to -:meth:`~pydrive2.drive.GoogleDrive.CreateFile`. -Save the image from the previous example into a specific folder``:`` +Set ``parents`` to a list containing the destination folder ID. This +example uploads the contents of a local image into that folder. .. code-block:: python - metadata = { - 'parents': [id_drive_folder], - 'name': 'image_test', - 'mimeType': 'image/jpeg' - } - # Create file - file = drive.CreateFile(metadata=metadata) - file.Upload() + image = drive.CreateFile({"parents": ["YOUR_FOLDER_ID"]}) + image.SetContentFile("cat.png") + image.Upload() Download file content --------------------- @@ -384,11 +295,12 @@ See the :download:`complete Python example <../examples/strip_bom_example.py>`. Abusive files ------------- -Files identified as `abusive`_ (malware, etc.) are only downloadable by the -owner. If you see a 'This file has been identified as malware or spam and -cannot be downloaded' error, set 'acknowledge_abuse=True' parameter in -`GetContentFile()`. By using it you indicate that you acknowledge the risks of -downloading potential malware. +If Drive flags a file as abusive, the owner or a shared-drive organizer +can explicitly acknowledge the risk when downloading it. Pass +``acknowledge_abuse=True`` to ``GetContentFile()`` for that download. +See the `files.get parameters`_ for the access requirements. + +.. _files.get parameters: https://developers.google.com/workspace/drive/api/reference/rest/v3/files/get .. _Drive API v3 file resource: https://developers.google.com/workspace/drive/api/reference/rest/v3/files#resource:-file @@ -398,7 +310,3 @@ downloading potential malware. https://developers.google.com/workspace/drive/api/guides/search-files#examples .. _add a byte order mark to plain-text exports: https://github.com/googleapis/google-api-nodejs-client/issues/2404 -.. _`abusive`: https://support.google.com/docs/answer/148505 - -.. _Drive v2 to v3 reference: - https://developers.google.com/workspace/drive/api/guides/v2-to-v3-reference diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 4ce5d67d..812245d8 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -9,7 +9,7 @@ Installation .. code-block:: sh - pip install 'pydrive2[fsspec]' + python -m pip install 'PyDrive2[fsspec]' The ``[fsspec]`` extra installs fsspec. If fsspec is already installed, installing plain PyDrive2 also registers ``gdrive://``. This registration @@ -66,9 +66,8 @@ Local webserver client_secret="my_client_secret", ) -By default, credentials will be cached per 'client_id', but if you are using -multiple users you might want to use 'profile' to avoid accidentally using -someone else's cached credentials: +The filesystem caches OAuth user credentials per client ID. Give each user +a separate ``profile`` when several users share a client ID and machine. .. code-block:: python @@ -81,14 +80,8 @@ someone else's cached credentials: profile="myprofile", ) -PyDrive2 2.x uses a separate default cache. The first interactive connection -after upgrading from 1.x prompts you to sign in. If you supplied a user -credential file explicitly, choose a fresh path. For DVC jobs that use -``GDRIVE_CREDENTIALS_DATA`` for a user account, replace that secret with the -newly saved JSON. Service-account jobs can reuse their configured key. - -Writing cached credentials to a file and using it if it already exists (which -avoids interactive auth): +To choose where PyDrive2 saves and refreshes your user token, set +``client_json_file_path``. For existing deployments, see :doc:`upgrading`. .. code-block:: python @@ -98,10 +91,10 @@ avoids interactive auth): "root", client_id="my_client_id", client_secret="my_client_secret", - client_json_file_path="/path/to/keyfile.json", + client_json_file_path="/path/to/user-token.json", ) -Using cached credentials from json string (avoids interactive auth): +To load saved user credentials from a JSON string, pass ``client_json``. .. code-block:: python @@ -117,30 +110,26 @@ Using cached credentials from json string (avoids interactive auth): Service account --------------- -Using json keyfile path: +Give the service account access to the folder and mount its ID. .. code-block:: python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( - # replace with ID of a drive or directory and give service account - # access to it - "root", + "FOLDER_ID", use_service_account=True, client_json_file_path="/path/to/keyfile.json", ) -Using json keyfile string: +You can also pass the service-account key as a JSON string. .. code-block:: python from pydrive2.fs import GDriveFileSystem fs = GDriveFileSystem( - # replace with ID of a drive or directory and give service account - # access to it - "root", + "FOLDER_ID", use_service_account=True, client_json=json_string, ) @@ -152,7 +141,8 @@ Additional parameters --------------------- :trash_only (bool): - Move files to trash instead of deleting. + Move files to the trash on removal (default: true). Set to false for + permanent deletion. :acknowledge_abuse (bool): Acknowledge the risk when downloading a file flagged as abusive. See :ref:`abusive-files`. @@ -162,14 +152,17 @@ Using filesystem .. code-block:: 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}") + fs.makedirs("FOLDER_ID/reports/2026", exist_ok=True) + for parent, directories, files in fs.walk("FOLDER_ID/reports"): + for name in files: + print(f"{parent}/{name}") - for fname in fnames: - print(f"file: {root}/{fname}") +``mkdir(path, create_parents=False)`` requires an existing parent. +``makedirs(path, exist_ok=True)`` creates missing parents and accepts an +existing directory. The filesystem caches directory IDs to speed up +repeated lookups. After an external move or deletion, use +``fs.invalidate_cache(path)`` for the affected path or +``fs.invalidate_cache()`` to clear the whole cache. For sequential reads, pass a positive ``block_size`` to ``fs.open()`` to set the Drive download request size in bytes. A writer buffers data locally, @@ -183,6 +176,6 @@ about and manipulating files, refer to fsspec docs on .. _`fsspec`: https://filesystem-spec.readthedocs.io/en/latest/ .. _domain-wide delegation: - https://developers.google.com/workspace/guides/create-credentials#set-up-domain-wide-delegation + https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority .. _`how to use a filesystem`: https://filesystem-spec.readthedocs.io/en/latest/usage.html#use-a-file-system diff --git a/docs/genindex.rst b/docs/genindex.rst deleted file mode 100644 index 9e530fa2..00000000 --- a/docs/genindex.rst +++ /dev/null @@ -1,2 +0,0 @@ -Index -===== diff --git a/docs/index.rst b/docs/index.rst index d576c9e9..c8c98241 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,43 +1,41 @@ -.. PyDrive2 documentation master file, created by - sphinx-quickstart on Sun Jun 12 23:01:40 2016. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +.. _welcome-to-pydrive2-s-documentation: -Welcome to PyDrive2's documentation! -==================================== +PyDrive2 documentation +====================== -PyDrive2 is a wrapper library of `google-api-python-client`_ that simplifies -many common Google Drive API tasks. +PyDrive2 2.0 is a Python client for Google Drive API v3 and an +fsspec-compatible filesystem for Google Drive. Use the :doc:`quickstart` +to sign in, upload a file, and list a folder. For path-based access with +``gdrive://`` URLs, see :doc:`fsspec`. -Project Info -============ +.. _how-to-install: -- Package: https://pypi.python.org/pypi/PyDrive2 -- Documentation: https://docs.iterative.ai/PyDrive2 -- Source: https://github.com/iterative/PyDrive2 -- Changelog: https://github.com/iterative/PyDrive2/releases +Installation +------------ -How to install -============== +PyDrive2 requires Python 3.11 or newer. -You can install PyDrive2 with regular ``pip`` command. +.. code-block:: sh -:: + python -m pip install PyDrive2 - $ pip install PyDrive2 +To use the fsspec filesystem, install the optional dependencies. -To install the current development version from GitHub, use: +.. code-block:: sh -:: + python -m pip install 'PyDrive2[fsspec]' - $ pip install git+https://github.com/iterative/PyDrive2.git#egg=PyDrive2 +.. _project-info: +The `DataChain team `_ maintains PyDrive2. +Find the source on `GitHub `_, +the package on `PyPI `_, and the +`release history `_ on GitHub. -.. _`google-api-python-client`: - https://github.com/google/google-api-python-client +.. _table-of-contents: -Table of Contents -================= +Guides and reference +-------------------- .. toctree:: :maxdepth: 2 @@ -47,5 +45,7 @@ Table of Contents filemanagement filelist fsspec + upgrading pydrive2 - genindex + +:ref:`genindex` diff --git a/docs/oauth.rst b/docs/oauth.rst index b4767008..cbf811c2 100644 --- a/docs/oauth.rst +++ b/docs/oauth.rst @@ -1,288 +1,154 @@ -OAuth made easy -=============== +.. _oauth-made-easy: -Authentication in two lines ---------------------------- +Authentication +============== + +.. _authentication-in-two-lines: + +Sign in from a local application +-------------------------------- -OAuth2.0 is complex and difficult to start with. To make it more simple, -*PyDrive2* makes all authentication into just two lines. +Follow :doc:`quickstart` to create a desktop OAuth client and download its +configuration as ``client_secrets.json``. PyDrive2 uses google-auth to +authorize requests to Drive. .. code-block:: python from pydrive2.auth import GoogleAuth gauth = GoogleAuth() - # Create local webserver and auto handles authentication. gauth.LocalWebserverAuth() -The :doc:`quickstart` registers ``http://localhost:8080/`` as the redirect -URI for a web application client. With that client, use -:meth:`~pydrive2.auth.GoogleAuth.LocalWebserverAuth` and keep port 8080 -available to receive the authorization code. +:meth:`~pydrive2.auth.GoogleAuth.LocalWebserverAuth` opens the browser and +listens on localhost, trying port 8080 and then 8090 by default. If you use +a web application client, register the exact callback URI, such as +``http://localhost:8080/``, and pass ``port_numbers=[8080]``. -To open the login URL yourself, call +To open the sign-in URL yourself, call ``gauth.LocalWebserverAuth(launch_browser=False)`` or -:meth:`~pydrive2.auth.GoogleAuth.CommandLineAuth`. Both print the URL -and wait for the same local callback. Open the URL in a browser that can -reach the callback port on the machine running PyDrive2. For unattended -jobs, use a service account or saved user credentials with a refresh token. +:meth:`~pydrive2.auth.GoogleAuth.CommandLineAuth`. Both print the URL and +wait for the same local callback. The browser must be able to reach the +callback on the machine running PyDrive2. Unattended jobs can use a saved +refresh token or a service account. -Automatic and custom authentication with *settings.yaml* --------------------------------------------------------- +.. _automatic-and-custom-authentication-with-settings-yaml: +.. _sample-settings-yaml: -Read this section if you need a custom authentication flow, **such as silent -authentication on a remote machine**. For an example of such a setup have a -look at `Sample settings.yaml`_. +Save credentials across runs +---------------------------- -OAuth is complicated and it requires a lot of settings. By default, -when you don't provide any settings, *PyDrive* will automatically set default -values which works for most of the cases. Here are some default settings. +By default, ``GoogleAuth()`` reads client configuration from +``client_secrets.json``, requests the Drive scope, and keeps the access token +in memory. To reuse a login, create ``settings.yaml`` in your working +directory and sign in once. -- Read client configuration from file *client_secrets.json* -- OAuth scope: :code:`https://www.googleapis.com/auth/drive` -- Don't save credentials -- Don't retrieve refresh token +.. code-block:: yaml -However, you might want to customize these settings while maintaining two lines -of clean code. If that is the case, you can make *settings.yaml* file in your -working directory and *PyDrive* will read it to customize authentication -behavior. - -These are all the possible fields of a *settings.yaml* file: - -.. code-block:: python - - 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**: ``http://localhost``. - **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): - Email address of the user the service account acts as through - `domain-wide delegation`_. - **Required**: No. -: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): - Save OAuth user credentials after signing in. A fresh login stays in - memory when this setting is false. When you load saved credentials, - PyDrive2 writes refreshed tokens back to the same file or dictionary key. - **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 the credentials file. Give the application a writable - directory for the lock and atomic file replacement. In containers, mount - the cache directory so the file can be replaced on refresh. - **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 scopes to request. - **Default**: ``['https://www.googleapis.com/auth/drive']``. - **Required**: No. - -.. _domain-wide delegation: - https://developers.google.com/workspace/guides/create-credentials#set-up-domain-wide-delegation - -Upgrading from PyDrive2 1.x -___________________________ - -Sign in once with PyDrive2 2.x to create new OAuth user credentials. Keep -your existing OAuth client ID and client secret. If you configured a cache, -choose a new ``save_credentials_file`` or ``save_credentials_key`` before -signing in. For unattended jobs, set ``get_refresh_token: True`` during -sign-in and provision the newly saved credentials before upgrading the job. - -Service accounts authenticate directly with their configured JSON or PKCS12 -key. Keep that key available to the application. If your deployment relied -solely on a saved 1.x service-account cache, provision its signing key. - -Sample *settings.yaml* -______________________ - -:: - - client_config_backend: settings - client_config: - client_id: 9637341109347.apps.googleusercontent.com - client_secret: psDskOoWr1P602PXRTHi - - save_credentials: True + client_config_backend: file + client_config_file: client_secrets.json + 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 + get_refresh_token: true + +The client configuration identifies your OAuth application. The separate +``credentials.json`` file contains the user's tokens. Give the application a +writable cache directory so it can lock and atomically replace the token +file on refresh. In containers, mount the directory. For an existing cache +from an earlier release, see :doc:`upgrading`. + +Settings reference +------------------ + +Pass a settings file path as ``GoogleAuth(settings_file="path/to/settings.yaml")`` +or supply a Python dictionary with ``GoogleAuth(settings=settings)``. + +``client_config_backend`` + Use ``file`` (the default) to read ``client_config_file``, + ``settings`` to supply a ``client_config`` dictionary, or ``service`` + with ``service_config`` for a service account. +``client_config`` + For the ``settings`` backend, provide ``client_id`` and ``client_secret``. + PyDrive2 supplies Google's ``auth_uri`` and ``token_uri`` and defaults + ``redirect_uri`` to ``http://localhost``. For a web callback, set + ``redirect_uri`` to the URI registered for the client. The optional + ``revoke_uri`` field defaults to null. +``oauth_scope`` + A list of OAuth scope URLs. The default is + ``https://www.googleapis.com/auth/drive``. Choose scopes that grant + access to the files your application needs. +``save_credentials`` and ``get_refresh_token`` + Both default to false. Enable both to save the login and request + offline access. Credentials loaded from a cache are written back to + that cache when refreshed. +``save_credentials_backend`` + When saving credentials, select ``file`` with ``save_credentials_file``, + or ``dictionary`` with ``save_credentials_dict`` and + ``save_credentials_key``. To access the updated value in your program, + pass the actual dictionary to ``GoogleAuth(settings=...)``. +``service_config`` + Supply the JSON signing key as a path (``client_json_file_path``), + dictionary (``client_json_dict``), or JSON string (``client_json``). + For a PKCS12 key, specify both ``client_pkcs12_file_path`` and + ``client_service_email``. For domain-wide delegation, set + ``client_user_email`` to the user the account should act as. Building your own authentication flow ------------------------------------- -You might want to build your own authentication flow. For example, you might -want to integrate your existing website with Drive API. In that case, you can -customize an authentication flow as follows: +For an application with its own web callback, configure a web OAuth client +and its registered redirect URI. Start a separate authorization flow per +login and keep the ``GoogleAuth`` instance and expected state in that user's +server-side session until the callback. The flow holds the PKCE verifier +needed for the token exchange. -1. Get the authorization URL from :meth:`~pydrive2.auth.GoogleAuth.GetAuthUrl`. -2. Direct the user to the authorization URL. Receive the authorization code at - the redirect URI registered for your application and verify the OAuth state - in the callback. -3. Pass the authorization code to :meth:`~pydrive2.auth.GoogleAuth.Auth` on - the same instance. Keep the flow for each login until the callback so the - exchange uses its original PKCE verifier. If a separate worker handles - the callback, retain the state and verifier in the user's server-side - session and restore the verifier on the flow before exchanging the code. +.. code-block:: python -Your *settings.yaml* will work for your customized authentication flow, too. + from secrets import compare_digest + from urllib.parse import parse_qs, urlsplit -Here is a sample code for your customized authentication flow + def start_login(): + gauth = GoogleAuth() + url = gauth.GetAuthUrl() + state = parse_qs(urlsplit(url).query)["state"][0] + return url, gauth, state -.. code-block:: python + def finish_login(gauth, expected_state, callback_params): + if not compare_digest(expected_state, callback_params.get("state", "")): + raise ValueError("OAuth state mismatch") + gauth.Auth(callback_params["code"]) - from pydrive2.auth import GoogleAuth - - # Configure your registered redirect URI in settings.yaml - gauth = GoogleAuth() - # Create authentication url user needs to visit - auth_url = gauth.GetAuthUrl() - # Your application handles the redirect - code = ReceiveVerifiedCallback(auth_url) - gauth.Auth(code) # Authorize and build service from the code +Redirect the user to the returned URL. On callback, retrieve and consume +the saved login from the session, then pass the decoded query parameters +to ``finish_login``. If several workers handle requests, the callback +worker needs the original verifier as well as the expected state. Authentication with a service account ------------------------------------- -A `Service account`_ is a special type of Google account intended to represent -a non-human user that needs to authenticate and be authorized to access data in -Google APIs. +Give the service account access to the Drive folder or files it will use. +To create files, use a shared drive where it can write, or configure +`domain-wide delegation`_ to act as a Workspace user with storage. -Typically, service accounts are used in scenarios such as: +.. code-block:: python -- Running workloads on virtual machines (VMs). -- Running workloads on data centers that call Google APIs. -- Running workloads which are not tied to the lifecycle of a human user. + from pydrive2.auth import GoogleAuth + from pydrive2.drive import GoogleDrive -If we use OAuth client ID we need to do one manual login into the account with -:meth:`~pydrive2.auth.GoogleAuth.LocalWebserverAuth`. If we use a service -account the login is automatic. + settings = { + "client_config_backend": "service", + "service_config": {"client_json_file_path": "service-account.json"}, + } + gauth = GoogleAuth(settings=settings) + gauth.ServiceAuth() + drive = GoogleDrive(gauth) +.. _domain-wide delegation: https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority -.. code-block:: python +.. _upgrading-from-pydrive2-1-x: - from pydrive2.auth import GoogleAuth - from pydrive2.drive import GoogleDrive +Upgrading saved credentials +--------------------------- - 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 - # Set oauth_scope here to request specific Drive permissions. - 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 - - -.. _`Service account`: - https://developers.google.com/workspace/guides/create-credentials#service-account +See :doc:`upgrading` for the first login, token cache, and service-account +changes in PyDrive2 2.0. diff --git a/docs/pydrive2.rst b/docs/pydrive2.rst index 762fbd18..92bb1fc4 100644 --- a/docs/pydrive2.rst +++ b/docs/pydrive2.rst @@ -1,5 +1,11 @@ -pydrive2 package -================ +.. _pydrive2-package: + +Python API reference +==================== + +Use :class:`~pydrive2.auth.GoogleAuth` to authenticate and +:class:`~pydrive2.drive.GoogleDrive` to work with files and listings. For +path-based operations, see :doc:`fsspec`. pydrive2.apiattr module ----------------------- @@ -45,4 +51,5 @@ pydrive2.fs module ------------------ .. autoclass:: pydrive2.fs.GDriveFileSystem + :members: __init__ :show-inheritance: diff --git a/docs/quickstart.rst b/docs/quickstart.rst index b6a15a03..52cbdc40 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -4,179 +4,107 @@ Quickstart Authentication -------------- -Drive API requires OAuth2.0 for authentication. *PyDrive2* makes your life much -easier by handling complex authentication steps for you. - -1. Go to `APIs Console`_ and make your own project. -2. Search for 'Google Drive API', select the entry, and click 'Enable'. -3. Select 'Credentials' from the left menu, click 'Create Credentials', select - 'OAuth client ID'. -4. Now, the product name and consent screen need to be set -> click 'Configure - consent screen' and follow the instructions. Once finished: - - a. Select 'Application type' to be *Web application*. - b. Enter an appropriate name. - c. Input *http://localhost:8080/* for 'Authorized redirect URIs'. - d. Click 'Create'. - -5. Click 'Download JSON' on the right side of Client ID to download - **client_secret_.json**. - -The downloaded file has all authentication information of your application. -**Rename the file to "client_secrets.json" and place it in your working -directory.** - -Create *quickstart.py* file and copy and paste the following code. +1. Enable the Google Drive API in your Google Cloud project and configure + the OAuth consent screen. If the app is in testing, add the account + you will use as a test user. +2. Create an OAuth client ID with application type **Desktop app** and + download its JSON configuration. Google's `Drive quickstart`_ walks + through the console setup. +3. Save the downloaded file as ``client_secrets.json`` in your working + directory. Run the following Python code and sign in when the browser + opens. PyDrive2 receives the authorization code on a local callback. .. code-block:: python from pydrive2.auth import GoogleAuth + from pydrive2.drive import GoogleDrive gauth = GoogleAuth() - # Creates local webserver and auto handles authentication. gauth.LocalWebserverAuth() + drive = GoogleDrive(gauth) -Run this code with *python quickstart.py* and you will see a web browser asking -you for authentication. Click *Accept* and you are done with authentication. -For more details, take a look at documentation: `OAuth made easy`_ - -.. _`APIs Console`: https://console.developers.google.com/iam-admin/projects -.. _`OAuth made easy`: /PyDrive2/oauth/ +The examples below use this ``drive`` object. To save credentials across +runs or use a service account, see :doc:`oauth`. Creating and Updating Files --------------------------- -There are many methods to create and update file metadata and contents. With -*PyDrive2*, all you have to know is `Upload()`_ method which makes optimal API -call for you. Add the following code to your *quickstart.py* and run it. +Create a local file object, set its content, and call +:meth:`~pydrive2.files.GoogleDriveFile.Upload` to create the file on Drive. +Call the same method to save later changes to the file. .. code-block:: python - from pydrive2.drive import GoogleDrive - - drive = GoogleDrive(gauth) - - # Create GoogleDriveFile instance with name 'Hello.txt'. - file1 = drive.CreateFile({'name': 'Hello.txt'}) - # Set content of the file from given string. - file1.SetContentString('Hello World!') - file1.Upload() + note = drive.CreateFile({"name": "Hello.txt"}) + note.SetContentString("Hello World!") + note.Upload() + print(note["id"]) -This code will create a new file with name *Hello.txt* and its content *Hello -World!*. You can see and open this file from `Google Drive`_ if you want. For -more details, take a look at documentation: `File management made easy`_ - -.. _`Upload()`: /PyDrive2/pydrive2/#pydrive2.files.GoogleDriveFile.Upload -.. _`Google Drive`: https://drive.google.com -.. _`File management made easy`: /PyDrive2/filemanagement/ + note["name"] = "Greetings.txt" + note.Upload() Listing Files ------------- -*PyDrive2* handles paginations and parses response as list of -`GoogleDriveFile`_. Let's get name and id of all the files in the root folder -of Google Drive. Again, add the following code to *quickstart.py* and execute -it. +List the entries in My Drive's root folder, excluding trashed items. +:meth:`~pydrive2.apiattr.ApiResourceList.GetList` collects all matching +pages when the query omits ``pageSize``. .. code-block:: 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('name: %s, id: %s' % (file1['name'], file1['id'])) + entries = drive.ListFile({"q": "'root' in parents and trashed=false"}).GetList() + for entry in entries: + print(entry["name"], entry["id"]) Creating a Folder ----------------- -GoogleDrive treats everything as a file and assigns different mimetypes for -different file formats. A folder is thus also a file with a special mimetype. -The code below allows you to add a subfolder to an existing folder. +A folder has the Drive folder MIME type. Set ``parents`` to a list +containing the destination folder ID. Use ``root`` for My Drive. .. code-block:: python - def create_folder(parent_folder_id, subfolder_name): - newFolder = drive.CreateFile({ - 'name': subfolder_name, - "parents": [parent_folder_id], - "mimeType": "application/vnd.google-apps.folder", - }) - newFolder.Upload() - return newFolder + folder = drive.CreateFile({ + "name": "Reports", + "mimeType": "application/vnd.google-apps.folder", + "parents": ["root"], + }) + folder.Upload() + note["parents"] = [folder["id"]] + note.Upload() Return File ID via File Name ------------------------------ +---------------------------- -A common task is providing the Google Drive API with a file id. -``get_id_of_name`` demonstrates a simple workflow to return the id of a file -handle by searching the file names in a given directory. The function takes -two arguments, ``name`` and ``parent_directory_id``. ``name`` is a string -that will be compared against file names included in a directory identified by -the ``parent_directory_id``. +Drive allows multiple entries with the same name. To find every matching +ID, list the parent folder and compare names. .. code-block:: python - def get_id_of_name(name, parent_directory_id): - foldered_list = drive.ListFile({ - 'q': "'" + parent_directory_id + "' in parents and trashed=false" - }).GetList() - for file in foldered_list: - if file['name'] == name: - return file['id'] - return None + def ids_for_name(parent_id, name): + query = {"q": f"'{parent_id}' in parents and trashed=false"} + return [ + item["id"] for item in drive.ListFile(query).GetList() + if item["name"] == name + ] + + print(ids_for_name(folder["id"], "Greetings.txt")) Browse Folders -------------- -This returns a json output of the data in a directory with some important -attributes like size, name, parent_id. +To browse a folder one page at a time, use its ID in a parent query. A +folder entry's ID can be used as the parent for the next listing. .. code-block:: python - browsed = [] - - def folder_browser(folder_list, parent_id): - for element in folder_list: - if type(element) is dict: - print(element['name']) - else: - print(element) - print( - "Enter Name of Folder You Want to Use\n" - "Enter '/' to use current folder\n" - "Enter ':' to create New Folder and use that" - ) - 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["name"] == folder_selected: - struc = element["list"] - browsed.append(folder_selected) - print("Inside " + folder_selected) - return folder_browser(struc, element['id']) - -here ``folder_list`` is the list of folders that is present - -You will see name and id of all the files and folders in root folder of your -Google Drive. For more details, refer to the documentation: -`File listing made easy`_ - -.. _`GoogleDriveFile`: /PyDrive2/pydrive2/#pydrive2.files.GoogleDriveFile -.. _`File listing made easy`: /PyDrive2/filelist/ + parent_id = folder["id"] + for page in drive.ListFile({"q": f"'{parent_id}' in parents and trashed=false"}): + for item in page: + print(item["id"], item["name"], item["mimeType"]) + +See :doc:`filemanagement` for downloads and permissions, and :doc:`filelist` +for pagination and field selection. + +.. _Drive quickstart: https://developers.google.com/workspace/drive/api/quickstart/python diff --git a/docs/upgrading.rst b/docs/upgrading.rst new file mode 100644 index 00000000..ecc8b33c --- /dev/null +++ b/docs/upgrading.rst @@ -0,0 +1,64 @@ +Upgrade to PyDrive2 2.0 +======================= + +PyDrive2 2.0 requires Python 3.11 or newer, authenticates with google-auth, +and uses Google Drive API v3. Drive file and folder IDs remain valid. + +Credentials +----------- + +Keep your OAuth client ID and secret. Sign in once with PyDrive2 2.0 to +create new user credentials. If you configured a cache, choose a new +``save_credentials_file`` or ``save_credentials_key`` before signing in. +For unattended jobs, enable ``get_refresh_token`` and ``save_credentials`` +during sign-in and provision the resulting token JSON. See :doc:`oauth`. + +The fsspec backend uses a separate default cache for 2.0. Its first +interactive connection prompts for a login. If you pass an explicit user +cache path, choose a new path. For DVC remotes that use +``GDRIVE_CREDENTIALS_DATA`` for a user account, replace its value with the +newly saved credentials. + +Service accounts use their configured JSON or PKCS12 signing key. Keep the +key available to the application. Deployments that relied solely on a +saved service-account token need to provision the signing key. + +Drive API fields and requests +----------------------------- + +Update metadata dictionaries, field masks, and search expressions to use +Drive v3 field names. + +.. list-table:: + :header-rows: 1 + :widths: 28 72 + + * - Drive API v2 + - Drive API v3 + * - ``title``, ``fileSize``, ``alternateLink`` + - ``name``, ``size``, ``webViewLink`` + * - ``labels.trashed`` + - Read ``trashed`` on the file itself. + * - Parent objects + - Pass one parent ID as a string, e.g. ``{"parents": [folder_id]}``. + Assign the new list and call ``Upload()`` to move an existing file. + * - ``maxResults``, ``items(...)`` + - Use ``pageSize`` and ``files(id,name)``. See :doc:`filelist` for + pagination and partial responses. + * - Permission ``value`` + - Use ``emailAddress`` for a user or group. For link sharing, set + ``allowFileDiscovery=False``. The notification request parameter + is now ``sendNotificationEmail`` (singular). + * - Upload option ``convert`` + - Set the destination Workspace MIME type in the file metadata and + pass the source MIME type as ``media_mime_type`` to ``Upload()``. + +File reads and listings request a subset of metadata by default. For +additional file fields, use ``FetchMetadata(fields="owners,capabilities")`` +or ``FetchMetadata(fetch_all=True)``. On listings, include ``id`` in a +custom selector when you will operate on the returned files. + +See :doc:`filemanagement` for a Workspace import example and Google's +`Drive v2 to v3 reference`_ for the full API mapping. + +.. _Drive v2 to v3 reference: https://developers.google.com/workspace/drive/api/guides/v2-to-v3-reference diff --git a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/README b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/README index 14696854..5b45901b 100644 --- a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/README +++ b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/README @@ -1,14 +1,18 @@ This script uploads a file to a folder on Google Drive. If the file can be converted into the Google format, such as a Google Sheet, it will be converted. -To run the script you need to complete the following steps: -1. Update settings.yaml with your: - - client ID, - - client secret, and - - credential storage path -2. Update upload.py with the location you save your settings.yaml file. This - can be an absolute or relative path. +Install PyDrive2 and enable the Drive API for your Google Cloud project. +Run from this example directory, with your desktop OAuth client configuration +saved as client_secrets.json. The script reads the adjacent settings.yaml +and saves user tokens in credentials.json in the working directory. + python upload.py FOLDER_ID /path/to/report.csv + +On the first run, open the printed URL in a browser that can reach the local +callback. Choose a destination folder accessible to this app and user with +the configured drive.file scope. A new CSV is imported as a Google Sheet +when Drive advertises that import format. One existing file visible to the app with the +same name is updated. Multiple matches stop the upload. This example is adapted from Evren Yurtesen (https://github.com/yurtesen/) with his consent. diff --git a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/settings.yaml b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/settings.yaml index 74a2bffe..d8ba02c8 100644 --- a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/settings.yaml +++ b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/settings.yaml @@ -1,17 +1,11 @@ # Original author: Evren Yurtesen - https://github.com/yurtesen/ -client_config_backend: settings -client_config: - client_id: - client_secret: - auth_uri: https://accounts.google.com/o/oauth2/auth - token_uri: https://accounts.google.com/o/oauth2/token - redirect_uri: urn:ietf:wg:oauth:2.0:oob - revoke_uri: +client_config_backend: file +client_config_file: client_secrets.json save_credentials: True save_credentials_backend: file -save_credentials_file: +save_credentials_file: credentials.json get_refresh_token: True diff --git a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/upload.py b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/upload.py index b4aea296..78d4a69d 100644 --- a/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/upload.py +++ b/examples/Upload-and-autoconvert-to-Google-Drive-Format-Example/upload.py @@ -10,30 +10,21 @@ import mimetypes import sys -from os import path +from pathlib import Path from pydrive2.auth import GoogleAuth from pydrive2.drive import GoogleDrive -from pydrive2.settings import LoadSettingsFile -# Update this value to the correct location. -# e.g. "/usr/local/scripts/pydrive/settings.yaml" -PATH_TO_SETTINGS_FILE = None -assert PATH_TO_SETTINGS_FILE is not None # Fail if path not specified. - -gauth = GoogleAuth() -gauth.settings = LoadSettingsFile(filename=PATH_TO_SETTINGS_FILE) -gauth.CommandLineAuth() -drive = GoogleDrive(gauth) - -# If provided arguments incorrect, print usage instructions and exit. -if len(sys.argv) < 3: - print("usage: upload.py ") - sys.exit(1) +if len(sys.argv) != 3: + sys.exit("usage: upload.py ") parentId = sys.argv[1] myFilePath = sys.argv[2] -myFileName = path.basename(sys.argv[2]) +myFileName = Path(myFilePath).name + +gauth = GoogleAuth(settings_file=Path(__file__).with_name("settings.yaml")) +gauth.CommandLineAuth() +drive = GoogleDrive(gauth) # Drive query string literals escape backslashes and single quotes. escaped_name = myFileName.replace("\\", "\\\\").replace("'", "\\'") @@ -43,6 +34,8 @@ } ).GetList() +# Drive name queries can include names that differ only in case. +file_list = [item for item in file_list if item["name"] == myFileName] # If file is found, update it, otherwise create new file. if len(file_list) > 1: sys.exit("Multiple files match. Choose a unique destination name.") diff --git a/examples/strip_bom_example.py b/examples/strip_bom_example.py index e1a1ae82..fbe4dc8d 100644 --- a/examples/strip_bom_example.py +++ b/examples/strip_bom_example.py @@ -19,40 +19,24 @@ # Print content before download. print("Original text:") -print(bytes(original_file_content.encode("unicode-escape"))) +print(repr(original_file_content)) print(f"Number of chars: {len(original_file_content)}") print() -# Original text: -# Generic, non-exhaustive\n ASCII test string. -# Number of chars: 43 - # Download document as text file WITH the BOM and print the contents. content_with_bom = file2.GetContentString(mimetype="text/plain") print("Content with BOM:") -print(bytes(content_with_bom.encode("unicode-escape"))) +print(repr(content_with_bom)) print(f"Number of chars: {len(content_with_bom)}") print() -# Content with BOM: -# \ufeffGeneric, non-exhaustive\r\n ASCII test string. -# Number of chars: 45 - # Download document as text file WITHOUT the BOM and print the contents. content_without_bom = file2.GetContentString( mimetype="text/plain", remove_bom=True ) print("Content without BOM:") -print(bytes(content_without_bom.encode("unicode-escape"))) +print(repr(content_without_bom)) print(f"Number of chars: {len(content_without_bom)}") -print() -# Content without BOM: -# Generic, non-exhaustive\r\n ASCII test string. -# Number of chars: 44 - -# *NOTE*: When downloading a Google Drive document as text file, line-endings -# are converted to the Windows-style: \r\n. - -# Delete the file as necessary. +# Remove the document created for this example. file1.Delete() diff --git a/pydrive2/auth.py b/pydrive2/auth.py index f2685d09..1873fb3f 100644 --- a/pydrive2/auth.py +++ b/pydrive2/auth.py @@ -109,9 +109,8 @@ def _decorated(self, *args, **kwargs): class GoogleAuth(ApiAttributeMixin): """Google Drive authentication using google-auth. - Loads all settings and credentials from one 'settings.yaml' file - and performs common OAuth2.0 related functionality such as authentication - and authorization. + Reads authentication settings from a dictionary or YAML file. User tokens + can be cached in a separate file or dictionary. """ DEFAULT_SETTINGS: ClassVar[dict[str, str | bool | list[str]]] = { @@ -368,7 +367,7 @@ def _storage_for(self, backend, filename=None): return store def LoadCredentials(self, backend=None): - """Loads credentials or create empty credentials if it doesn't exist. + """Load user credentials, setting credentials to None if the cache is empty. :param backend: target backend to save credential to. :type backend: str. @@ -380,7 +379,7 @@ def LoadCredentials(self, backend=None): self._load_credentials(self._storage_for("dictionary")) def LoadCredentialsFile(self, credentials_file=None): - """Loads credentials or create empty credentials if it doesn't exist. + """Load user credentials, setting credentials to None if the cache is empty. Loads credentials file from path in settings if not specified. diff --git a/pydrive2/files.py b/pydrive2/files.py index a796a86e..bcc8e1c0 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -339,7 +339,7 @@ def GetContentString( :param remove_bom: Whether to strip a known BOM. :type remove_bom: bool - :returns: str -- utf-8 decoded content of the file + :returns: File content decoded with the requested encoding. :raises: ApiRequestError, FileNotUploadedError, FileNotDownloadableError """ stale = not self.dirty["content"] and ( @@ -402,7 +402,10 @@ def GetContentIOBuffer( chunksize=DEFAULT_CHUNK_SIZE, acknowledge_abuse=False, ): - """Get a file-like object which has a buffered read() method. + """Return a sequential reader over Drive download or export chunks. + + Iterate over the reader or call its read() method once per chunk. + Chunks are bytes unless an encoding is supplied. :param mimetype: mimeType of the file. :type mimetype: str @@ -678,8 +681,6 @@ def DeletePermission(self, permission_id): :param permission_id: The permission id. :type permission_id: str - :return: True if it succeeds. - :rtype: bool """ request = self.auth.service.permissions().delete( fileId=self._FileId(), diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 13701995..59f92abc 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -268,20 +268,20 @@ def __init__( :param client_user_email: User email that authority was delegated to (only for service account). :type client_user_email: str. - :param client_json: JSON keyfile loaded into a string. + :param client_json: Saved user credentials or a service-account key as JSON. :type client_json: str. - :param client_json_file_path: Path to JSON keyfile. + :param client_json_file_path: User token cache or service-account key path. :type client_json_file_path: str. :param use_service_account: Use service account. :type use_service_account: bool. :param profile: Profile name for caching credentials (ignored for service account). + :type profile: str. :param trash_only: Move files to trash instead of deleting. :type trash_only: bool. :param acknowledge_abuse: Acknowledging the risk and download file identified as abusive. :type acknowledge_abuse: bool - :type profile: str. :raises: GDriveAuthError """ super().__init__(**kwargs) diff --git a/pydrive2/test/README.rst b/pydrive2/test/README.rst index 641affcd..790caa3b 100644 --- a/pydrive2/test/README.rst +++ b/pydrive2/test/README.rst @@ -1,79 +1,45 @@ Run tests locally ------------------ +================= -After installing the test dependencies, run the offline tests from the -repository root. +From the repository root, install the test dependencies with Python 3.11 +or newer and run the offline suite. -.. code-block:: console +.. code-block:: sh + python -m pip install -e '.[tests,fsspec]' python -m pytest -m "not manual and not drive" -Mark tests that need Drive credentials with ``pytest.mark.drive``. To run -those tests locally, configure a service account as described below. +Live Drive tests +---------------- -1. Copy settings files to the :code:`pydrive2/test/settings/local` directory: +The ``drive`` tests make real Google Drive requests, including creating, +sharing, and deleting test files. Use a dedicated test account with the +Drive API enabled. The filesystem tests create files under the account's +``root`` and require write access and storage there. - :: +For the noninteractive suite, set ``GDRIVE_USER_CREDENTIALS_DATA`` to the +**contents of a service-account JSON key**. Some tests read this variable +directly. The helpers also write it to ``/tmp/pydrive2/credentials.json`` +and prepare local copies of the settings templates. Run locally in a +private test environment and remove the generated credential files when +finished. - cd pydrive2/test/settings && cp *.yaml local +.. code-block:: sh -2. Setup a Google service account for your Google Cloud Project: + python -m pytest -m "drive and not manual" - - Sign into the `Google API Console`_ - - Select or `Create a new`_ project. - - `Enable the Drive API`_ from the **APIs & Services** **Dashboard** (left - sidebar), click on **+ ENABLE APIS AND SERVICES**. Find and select the - "Google Drive API" in the API Library, and click on the **ENABLE** button. - - Go back to **IAM & Admin** in the left sidebar, and select - **Service Accounts**. Click **+ CREATE SERVICE ACCOUNT**, on the next - screen, enter **Service account name** e.g. "PyDrive tests", and click - **Create**. Select **Continue** at the next - **Service account permissions** page, click at **+ CREATE KEY**, select - **JSON** and **Create**. Save generated :code:`.json` key file at your - local disk. - - Copy downloaded :code:`json` file to - :code:`/tmp/pydrive2/credentials.json` directory. +Manual OAuth tests +------------------ -3. Optional. If you would like to use your own an OAuth client ID follow the - steps: +Tests marked ``manual`` require interaction. For local browser sign-in, use +a desktop OAuth client. Place its downloaded configuration in +``pydrive2/test/client_secrets.json`` locally and configure the corresponding +test settings under ``pydrive2/test/settings/local/`` when using inline client +settings. Run the desired test by node ID, for example: - - Under `Google API Console`_ select **APIs & Services** from the left - sidebar, and select **OAuth consent screen**. Chose a **User Type** and - click **CREATE**. On the next screen, enter an **Application name** e.g. - "PyDrive tests", and click the **Save** (scroll to bottom). - - From the left sidebar, select **Credentials**, and click the - **Create credentials** dropdown to select **OAuth client ID**. Chose - **Other** and click **Create** to proceed with a default client name. - At **Credentials** screen find a list of your **OAuth 2.0 Client IDs**, - click download icon in front of your OAuth client id created previously. - You should be prompted to download :code:`client_secret_xxx_.json` file. - - Copy downloaded :code:`.json` file into :code:`pydrive2/test` directory - and rename to :code:`client_secrets.json`. - - Replace {{ }} sections in - :code:`pydrive2/test/settings/local/test_oauth_test_02.yaml` with the - relevant values of :code:`client_id` and :code:`client_secret` from your - **client_secrets.json** file. +.. code-block:: sh -4. Setup virtual environment (recommended optional step): + python -m pytest -m manual pydrive2/test/test_oauth.py -k test_01 - :: - - virtualenv -p python .env - source .env/bin/activate - -5. Install :code:`tests` deps from the root directory of the project: - - :: - - pip install -e .[tests,fsspec] - -6. Run tests: - - :: - - py.test -v -s - -.. _Google API Console: https://console.developers.google.com -.. _Create a new: - https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project -.. _Enable the Drive API: https://developers.google.com/workspace/drive/api/guides/about-sdk +Keep local credentials and changes to the example client configuration out +of commits.