Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions .flake8

This file was deleted.

6 changes: 3 additions & 3 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7

- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: '3.8'
python-version: '3.12'

- name: Build
run: |
Expand Down
16 changes: 13 additions & 3 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: pre-commit/action@v3.0.1
- uses: actions/checkout@v7
- uses: astral-sh/ruff-action@v4.1.0
- run: ruff format --check .

types:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
- run: python -m pip install -e '.[fsspec,tests,typing]'
- run: python -m mypy
6 changes: 3 additions & 3 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7

- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: '3.8'
python-version: '3.12'

- name: Install pypa/build
run: python -m pip install build
Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ on:
branches:
- main
pull_request_target:
workflow_dispatch:

name: Tests

Expand All @@ -24,15 +25,15 @@ jobs:
max-parallel: 3
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
pyv: ["3.9", "3.10", "3.11", "3.12"]
pyv: ["3.11", "3.12", "3.13", "3.14", "3.15"]

steps:
- uses: actions/checkout@v4
with:
# NOTE: needed for pull_request_target to use PR code
ref: ${{ github.event.pull_request.head.sha || github.ref }}

- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.pyv }}

Expand Down
16 changes: 6 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
repos:
- hooks:
- id: black
language_version: python3
repo: https://github.com/psf/black
rev: 23.12.1
- hooks:
- id: flake8
language_version: python3
repo: https://github.com/PyCQA/flake8
rev: 6.0.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.6
hooks:
- id: ruff-check
- id: ruff-format
types_or: [python, pyi]
4 changes: 4 additions & 0 deletions CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ Contributing code

If you have improvements to PyDrive2, send us your pull requests! For those
just getting started, Github has a `howto <https://help.github.com/articles/using-pull-requests/>`_.

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.
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Features of PyDrive2
How to install
--------------

You can install PyDrive2 with regular ``pip`` command.
PyDrive2 requires Python 3.11 or newer. Install it with ``pip``.

::

Expand Down
3 changes: 1 addition & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# PyDrive2 documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 12 23:01:40 2016.
Expand All @@ -12,8 +11,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sys

# 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
usage: upload.py <Google Drive folder ID> <local file path>
example usage: upload.py 0B5XXXXY9KddXXXXXXXA2c3ZXXXX /path/to/my/file
"""

import sys
from os import path

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
from pydrive2.settings import LoadSettingsFile
Expand All @@ -24,9 +26,9 @@
drive = GoogleDrive(gauth)

# If provided arguments incorrect, print usage instructions and exit.
if len(sys.argv) < 2:
if len(sys.argv) < 3:
print("usage: upload.py <Google Drive folder ID> <local file path>")
exit(1) # Exit program as incorrect parameters provided.
sys.exit(1)

parentId = sys.argv[1]
myFilePath = sys.argv[2]
Expand All @@ -35,9 +37,7 @@
# Check if file name already exists in folder.
file_list = drive.ListFile(
{
"q": '"{}" in parents and title="{}" and trashed=false'.format(
parentId, myFileName
)
"q": f'"{parentId}" in parents and title="{myFileName}" and trashed=false'
}
).GetList()

Expand Down
12 changes: 6 additions & 6 deletions examples/strip_bom_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
# Print content before download.
print("Original text:")
print(bytes(original_file_content.encode("unicode-escape")))
print("Number of chars: %d" % len(original_file_content))
print("")
print(f"Number of chars: {len(original_file_content)}")
print()
# Original text:
# Generic, non-exhaustive\n ASCII test string.
# Number of chars: 43
Expand All @@ -31,8 +31,8 @@
content_with_bom = file2.GetContentString(mimetype="text/plain")
print("Content with BOM:")
print(bytes(content_with_bom.encode("unicode-escape")))
print("Number of chars: %d" % len(content_with_bom))
print("")
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
Expand All @@ -44,8 +44,8 @@
)
print("Content without BOM:")
print(bytes(content_without_bom.encode("unicode-escape")))
print("Number of chars: %d" % len(content_without_bom))
print("")
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
Expand Down
2 changes: 1 addition & 1 deletion examples/using_folders.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
# Get folder info and print to screen.
folder_title = folder["title"]
folder_id = folder["id"]
print("title: %s, id: %s" % (folder_title, folder_id))
print(f"title: {folder_title}, id: {folder_id}")

# Upload file to folder.
f = drive.CreateFile(
Expand Down
2 changes: 1 addition & 1 deletion pydrive2/__pyinstaller/hook-googleapiclient.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from PyInstaller.utils.hooks import ( # pylint: disable=import-error
copy_metadata,
collect_data_files,
copy_metadata,
)

datas = copy_metadata("google-api-python-client")
Expand Down
17 changes: 3 additions & 14 deletions pydrive2/__pyinstaller/test_hook-googleapiclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,14 @@

from PyInstaller import __main__ as pyi_main


# NOTE: importlib.resources.contents is available in py3.7+, but due to how
# pyinstaller handles importlib, we need to use the importlib_resources
# backport if there are any resources methods that are not available in a given
# python version, which ends up being py<3.10
_APP_SOURCE = """
import sys
if sys.version_info >= (3, 10):
from importlib.resources import contents
else:
from importlib_resources import contents
from importlib.resources import files

import pydrive2.files


cache_files = contents(
"googleapiclient.discovery_cache.documents"
)
assert len(cache_files) > 0
documents = files("googleapiclient.discovery_cache.documents")
assert documents.joinpath("drive.v2.json").is_file()
"""


Expand Down
7 changes: 4 additions & 3 deletions pydrive2/apiattr.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ def GetChanges(self):
"""
dirty = {}
for key in self:
if self.metadata.get(key) is None:
dirty[key] = self[key]
elif self.metadata[key] != self[key]:
if (
self.metadata.get(key) is None
or self.metadata[key] != self[key]
):
dirty[key] = self[key]
return dirty

Expand Down
56 changes: 30 additions & 26 deletions pydrive2/auth.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import os
import json
import webbrowser
import httplib2
import oauth2client.clientsecrets as clientsecrets
import os
import threading
import webbrowser
from functools import wraps
from typing import ClassVar

import httplib2
from googleapiclient.discovery import build
from functools import wraps
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import OOB_CALLBACK_URN
from oauth2client import clientsecrets
from oauth2client._helpers import scopes_to_string
from oauth2client.client import (
OOB_CALLBACK_URN,
AccessTokenRefreshError,
FlowExchangeError,
OAuth2WebServerFlow,
)
from oauth2client.contrib.dictionary_storage import DictionaryStorage
from oauth2client.file import Storage
from oauth2client.tools import ClientRedirectHandler
from oauth2client.tools import ClientRedirectServer
from oauth2client._helpers import scopes_to_string
from .apiattr import ApiAttribute
from .apiattr import ApiAttributeMixin
from .settings import LoadSettingsFile
from .settings import ValidateSettings
from .settings import SettingsError
from .settings import InvalidConfigError
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.tools import ClientRedirectHandler, ClientRedirectServer

from .apiattr import ApiAttribute, ApiAttributeMixin
from .settings import (
InvalidConfigError,
LoadSettingsFile,
SettingsError,
ValidateSettings,
)


class AuthError(Exception):
Expand Down Expand Up @@ -150,21 +154,21 @@ class GoogleAuth(ApiAttributeMixin):
and authorization.
"""

DEFAULT_SETTINGS = {
DEFAULT_SETTINGS: ClassVar[dict[str, str | bool | list[str]]] = {
"client_config_backend": "file",
"client_config_file": "client_secrets.json",
"save_credentials": False,
"oauth_scope": ["https://www.googleapis.com/auth/drive"],
}
CLIENT_CONFIGS_LIST = [
CLIENT_CONFIGS_LIST: ClassVar[list[str]] = [
"client_id",
"client_secret",
"auth_uri",
"token_uri",
"revoke_uri",
"redirect_uri",
]
SERVICE_CONFIGS_LIST = ["client_user_email"]
SERVICE_CONFIGS_LIST: ClassVar[list[str]] = ["client_user_email"]
settings = ApiAttribute("settings")
client_config = ApiAttribute("client_config")
flow = ApiAttribute("flow")
Expand Down Expand Up @@ -381,7 +385,7 @@ def _InitializeStoragesFromSettings(self):
result[backend] = DictionaryStorage(creds_dict, creds_key)
elif save_credentials:
raise InvalidConfigError(
"Unknown save_credentials_backend: %s" % backend
f"Unknown save_credentials_backend: {backend}"
)
return result, result.get(backend)

Expand Down Expand Up @@ -549,7 +553,7 @@ def LoadClientConfigFile(self, client_config_file=None):
client_config_file
)
except clientsecrets.InvalidClientSecretsError as error:
raise InvalidConfigError("Invalid client secrets file %s" % error)
raise InvalidConfigError(f"Invalid client secrets file {error}")
if client_type not in (
clientsecrets.TYPE_WEB,
clientsecrets.TYPE_INSTALLED,
Expand Down Expand Up @@ -681,7 +685,7 @@ def Refresh(self):
try:
self.credentials.refresh(self.http)
except AccessTokenRefreshError as error:
raise RefreshError("Access token refresh failed: %s" % error)
raise RefreshError(f"Access token refresh failed: {error}")

def GetAuthUrl(self):
"""Creates authentication url where user visits to grant access.
Expand Down Expand Up @@ -714,7 +718,7 @@ def Authenticate(self, code):
try:
self.credentials = self.flow.step2_exchange(code)
except FlowExchangeError as e:
raise AuthenticationError("OAuth2 code exchange failed: %s" % e)
raise AuthenticationError(f"OAuth2 code exchange failed: {e}")
print("Authentication successful.")

def _build_http(self):
Expand Down
3 changes: 1 addition & 2 deletions pydrive2/drive.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from .apiattr import ApiAttributeMixin
from .files import GoogleDriveFile
from .files import GoogleDriveFileList
from .auth import LoadAuth
from .files import GoogleDriveFile, GoogleDriveFileList


class GoogleDrive(ApiAttributeMixin):
Expand Down
Loading
Loading