tempest_fastapi_sdk.integrations.storage.google_drive¶
Google Drive como backend de UploadUtils: upload para uma pasta compartilhada.
storage
¶
Google Drive as an :class:~tempest_fastapi_sdk.utils.UploadStorage backend.
Drive addresses files by id, not by path, and two files in one folder may
share a name. So the key an
:class:~tempest_fastapi_sdk.utils.UploadUtils hands the backend is stored
in the file's appProperties (private to this app) under
:data:TEMPEST_KEY_PROPERTY, and every lookup searches that property inside
the configured folder::
'<folder>' in parents
and appProperties has { key='tempest_key' and value='<key>' }
and trashed = false
The file's name is only for people browsing the folder: the last
segment of the key.
Writing a key that already exists replaces the content of that file —
same id, same link, new media (files.update) — instead of creating a
second file, matching what the local and MinIO backends do with an existing
key. Two writes racing on a brand-new key can still both create a file:
Drive has no conditional create. :meth:GoogleDriveUploadStorage.exists
then answers True, :meth:GoogleDriveUploadStorage.delete removes every
match, and the next write replaces the first match.
TEMPEST_KEY_PROPERTY
module-attribute
¶
The appProperties key that holds the UploadStorage key.
APP_PROPERTY_MAX_BYTES
module-attribute
¶
Drive's documented ceiling for one property, key plus value, in UTF-8.
From "Add custom file properties" (https://developers.google.com/workspace/drive/api/guides/properties). Enforced here so a long key fails before any byte is sent instead of at the API; not measured against the live service.
GOOGLE_DRIVE_BACKEND
module-attribute
¶
Backend name carried by :class:PresignedUrlUnsupportedException.
DEFAULT_HTTP_TIMEOUT_SECONDS
module-attribute
¶
Timeout of the httpx.AsyncClient built by from_service_account.
GoogleDriveUploadStorage
¶
GoogleDriveUploadStorage(
client: GoogleDriveClient,
*,
folder_id: str,
drive_id: str | None = None,
http_client: AsyncClient | None = None,
)
:class:~tempest_fastapi_sdk.utils.UploadStorage on a Google Drive folder.
Plug it into :class:~tempest_fastapi_sdk.utils.UploadUtils unchanged::
storage = GoogleDriveUploadStorage.from_service_account(
**settings.google_drive_kwargs()
)
uploads = UploadUtils(backend=storage, max_size_bytes=10 * 1024 * 1024)
Validation (extension, MIME, size, magic bytes) stays in UploadUtils;
this backend runs validator on the first chunk before opening
the upload session, and stops at max_size_bytes mid-stream — the
resumable session is then abandoned before its last piece, which, as
Google's upload guide describes the session, should leave no file
(not measured against the live service).
Initialize the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
GoogleDriveClient
|
A configured Drive client. |
required |
folder_id
|
str
|
Folder every file is written into and searched in. It must be shared with the client's account. |
required |
drive_id
|
str | None
|
Shared Drive holding the folder; narrows
searches to it. |
None
|
http_client
|
AsyncClient | None
|
An HTTP client this
backend owns and closes in :meth: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
from_service_account
classmethod
¶
from_service_account(
*,
folder_id: str,
credentials_path: str | Path | None = None,
credentials_json: str | None = None,
drive_id: str | None = None,
http_client: AsyncClient | None = None,
scopes: Sequence[str] = (DRIVE_SCOPE,),
chunk_size: int = DEFAULT_UPLOAD_CHUNK_SIZE,
) -> GoogleDriveUploadStorage
Build the backend from a service-account key.
The keywords folder_id, credentials_path,
credentials_json and drive_id are what
:meth:~tempest_fastapi_sdk.settings.GoogleDriveSettings.google_drive_kwargs
returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_id
|
str
|
Target folder id. |
required |
credentials_path
|
str | Path | None
|
Service-account key file. |
None
|
credentials_json
|
str | None
|
The key inline; wins over the file. |
None
|
drive_id
|
str | None
|
Shared Drive holding the folder. |
None
|
http_client
|
AsyncClient | None
|
Client for the token
endpoint and the API. |
None
|
scopes
|
Sequence[str]
|
OAuth scopes. Defaults to full Drive. |
(DRIVE_SCOPE,)
|
chunk_size
|
int
|
Resumable piece size, a multiple of 256 KiB. |
DEFAULT_UPLOAD_CHUNK_SIZE
|
Returns:
| Name | Type | Description |
|---|---|---|
GoogleDriveUploadStorage |
GoogleDriveUploadStorage
|
The backend. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When no credentials are given, they are not a
service-account key, or |
OSError
|
When the key file cannot be read. |
find
async
¶
find(key: str) -> list[GoogleDriveFile]
Return every non-trashed file in the folder stored under key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Type | Description |
|---|---|
list[GoogleDriveFile]
|
list[GoogleDriveFile]: The matches — normally zero or one; |
list[GoogleDriveFile]
|
|
Raises:
| Type | Description |
|---|---|
GoogleDriveFolderNotFoundException
|
When Drive answers |
GoogleDriveException
|
On any other error answer. |
write_stream
async
¶
write_stream(
key: str,
chunks: AsyncIterator[bytes],
*,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
max_size_bytes: int | None = None,
validator: ContentValidator | None = None,
) -> UploadResult
Upload chunks to the folder under key.
When a file with key already exists its content is replaced
(same id and link); otherwise a file named after the key's last
segment is created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key, stored in |
required |
chunks
|
AsyncIterator[bytes]
|
Source stream. |
required |
content_type
|
str
|
MIME type stored on the file. |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
Extra |
None
|
max_size_bytes
|
int | None
|
Abort once the stream exceeds it. |
None
|
validator
|
ContentValidator | None
|
Run on the first chunk, before any request to Drive. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UploadResult |
UploadResult
|
|
UploadResult
|
when it reports none), and |
|
UploadResult
|
|
|
UploadResult
|
with access to the file, not a download URL. |
When the write fails for any reason, chunks is closed
(aclose) if it is an async generator, so a caller's finally
runs right away instead of when the generator is collected.
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the key or a metadata property is too
long for a Drive property ( |
InvalidFileTypeException
|
When |
FileTooLargeException
|
When |
GoogleDriveFolderNotFoundException
|
When the folder is missing
or not shared with the account (a |
GoogleDriveException
|
On any other Drive error — including a
|
delete
async
¶
Permanently delete every file stored under key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when none matched. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On a Drive error. |
exists
async
¶
Return whether a file is stored under key in the folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On a Drive error. |
web_view_link
async
¶
Return the Drive link of the file under key.
Permanent, and it opens only for someone with Drive access to the file — useful in an admin screen, not as a public download URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The |
str | None
|
matches. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On a Drive error. |
presigned_url
async
¶
Refuse: Google Drive has no presigned URLs.
Drive serves a file to callers holding a Drive permission; there is
no temporary signed link to mint, and returning the permanent
webViewLink here would let a caller treat it as one that
expires. Stream the file through an authenticated route of your
own, or read :meth:web_view_link when a Drive link is what you
want.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key (unused). |
required |
expires
|
timedelta
|
Requested lifetime (unused). |
timedelta(hours=1)
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: Never returns. |
Raises:
| Type | Description |
|---|---|
PresignedUrlUnsupportedException
|
Always ( |
client
¶
An async client for the Drive API v3 calls an upload backend needs.
Five calls, each written from Google's reference
(https://developers.google.com/workspace/drive/api/reference/rest/v3/files):
files.list, files.get, files.delete, and files.create /
files.update through the resumable upload protocol
(https://developers.google.com/workspace/drive/api/guides/manage-uploads#resumable).
Every call sends supportsAllDrives=true, so a folder inside a Shared
Drive behaves like one in My Drive.
The resumable upload streams in pieces of a multiple of 256 KiB (the
protocol's granularity). Each piece that is not the last says
Content-Range: bytes <first>-<last>/*; the server answers
308 Resume Incomplete with a Range: bytes=0-<n> header naming what
it kept, and the next piece starts right after it, so bytes the server did
not keep are re-sent and nothing else is. The client reads one piece
ahead, so the last PUT always carries bytes and the total — a
payload that is an exact multiple of the piece size never ends on an empty
bytes */<total>, which the protocol also uses as a status query. The
only empty closing PUT is the zero-byte file's bytes */0.
A 429/5xx, a 403 whose reason is rateLimitExceeded or
userRateLimitExceeded, or a transport error is retried with
exponential backoff — or after the Retry-After seconds of a
429/503, capped at backoff_max_seconds — up to max_retries
times. On a piece, the client first asks the session how much it holds
(Content-Range: bytes */<total or *>); the stream already sent is
never replayed. A 404 on a piece or a status query means the session
itself is gone (reason :data:UPLOAD_SESSION_NOT_FOUND_REASON).
DRIVE_API_BASE_URL
module-attribute
¶
Base URL of the Drive API v3 metadata endpoints.
DRIVE_UPLOAD_BASE_URL
module-attribute
¶
Base URL of the Drive API v3 media upload endpoints.
UPLOAD_CHUNK_GRANULARITY
module-attribute
¶
Every piece but the last must be a multiple of this (256 KiB).
DEFAULT_UPLOAD_CHUNK_SIZE
module-attribute
¶
DEFAULT_UPLOAD_CHUNK_SIZE: int = 32 * UPLOAD_CHUNK_GRANULARITY
Default piece size of a resumable upload: 8 MiB.
DEFAULT_MAX_RETRIES
module-attribute
¶
How many times one request or one piece is retried on a transient error.
RETRYABLE_STATUSES
module-attribute
¶
Statuses retried with backoff; every other error but a rate-limit 403
is raised at once.
RATE_LIMIT_REASONS
module-attribute
¶
error.errors[].reason values that make a 403 retryable.
Drive reports per-user and per-project quota as 403 with one of these
reasons (https://developers.google.com/workspace/drive/api/guides/handle-errors).
RETRY_AFTER_STATUSES
module-attribute
¶
Statuses whose Retry-After (in seconds) replaces the backoff delay.
UPLOAD_SESSION_NOT_FOUND_REASON
module-attribute
¶
reason of the error raised when a resumable session answers 404.
FILE_FIELDS
module-attribute
¶
The fields mask requested for every file resource.
RESUME_INCOMPLETE
module-attribute
¶
Status of a resumable session that has not received the whole file yet.
GoogleDriveFile
dataclass
¶
GoogleDriveFile(
id: str,
name: str,
mime_type: str | None = None,
size: int | None = None,
web_view_link: str | None = None,
app_properties: dict[str, str] = dict(),
)
The parts of a Drive File resource this client reads.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
The file id. |
name |
str
|
The display name. |
mime_type |
str | None
|
The stored MIME type. |
size |
int | None
|
Size in bytes; Drive sends it as a string and omits it for Google Docs-type files. |
web_view_link |
str | None
|
The link that opens the file in Drive, for someone with access to it. Not a download URL and not temporary. |
app_properties |
dict[str, str]
|
Private properties set by this app. |
from_resource
classmethod
¶
from_resource(resource: Mapping[str, object]) -> GoogleDriveFile
Parse a File resource as returned by the API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource
|
Mapping[str, object]
|
The decoded JSON object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
GoogleDriveFile |
GoogleDriveFile
|
The parsed file. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
When the resource has no |
GoogleDriveClient
¶
GoogleDriveClient(
*,
token_provider: AccessTokenProvider,
http_client: AsyncClient,
principal_email: str | None = None,
chunk_size: int = DEFAULT_UPLOAD_CHUNK_SIZE,
max_retries: int = DEFAULT_MAX_RETRIES,
backoff_base_seconds: float = 0.5,
backoff_max_seconds: float = 16.0,
sleep: Callable[[float], Awaitable[None]] = sleep,
api_base_url: str = DRIVE_API_BASE_URL,
upload_base_url: str = DRIVE_UPLOAD_BASE_URL,
)
Async Drive API v3 client over an injected httpx.AsyncClient.
Safe to share between concurrent requests: it keeps no per-call state, and the token provider serializes its own refresh.
Initialize the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_provider
|
AccessTokenProvider
|
Source of bearer tokens. |
required |
http_client
|
AsyncClient
|
The caller owns and closes it. |
required |
principal_email
|
str | None
|
The account the token belongs to, named in folder-not-found messages. |
None
|
chunk_size
|
int
|
Piece size of a resumable upload; a positive
multiple of :data: |
DEFAULT_UPLOAD_CHUNK_SIZE
|
max_retries
|
int
|
Retries per request or piece on
|
DEFAULT_MAX_RETRIES
|
backoff_base_seconds
|
float
|
First backoff delay; doubles per attempt. |
0.5
|
backoff_max_seconds
|
float
|
Ceiling of one backoff delay. |
16.0
|
sleep
|
Callable[[float], Awaitable[None]]
|
Awaited between attempts; tests inject a no-op. |
sleep
|
api_base_url
|
str
|
Metadata endpoint root. |
DRIVE_API_BASE_URL
|
upload_base_url
|
str
|
Upload endpoint root. |
DRIVE_UPLOAD_BASE_URL
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
list_files
async
¶
list_files(
query: str, *, drive_id: str | None = None, page_size: int = 100
) -> list[GoogleDriveFile]
Run files.list and follow every page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
A Drive |
required |
drive_id
|
str | None
|
Restrict the search to this Shared Drive
( |
None
|
page_size
|
int
|
Page size requested. |
100
|
Returns:
| Type | Description |
|---|---|
list[GoogleDriveFile]
|
list[GoogleDriveFile]: Matching files; |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On an error answer. |
get_file
async
¶
get_file(file_id: str) -> GoogleDriveFile
Run files.get for metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_id
|
str
|
The file id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
GoogleDriveFile |
GoogleDriveFile
|
The file. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On an error answer ( |
delete_file
async
¶
Run files.delete — permanent, the file skips the trash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_id
|
str
|
The file id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
|
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On any other error answer. |
upload
async
¶
upload(
chunks: AsyncIterator[bytes],
*,
metadata: Mapping[str, object],
content_type: str,
file_id: str | None = None,
) -> GoogleDriveFile
Stream chunks through a resumable session.
The first piece is read from chunks before the session is
opened, so an iterator that raises on its first chunk (a content
validator) leaves nothing behind on Drive. Google's upload guide
describes the file as created when the session completes, so an
exception raised by chunks mid-stream, which abandons the
session before its last piece, is expected to leave no file —
not measured against the live service. When the upload fails,
chunks is closed (aclose) if it is an async generator.
The stream is read one piece ahead: a piece goes out with
/* only while more bytes are known to follow, so the last
PUT always carries bytes and the total. The zero-byte file is
the exception — it is closed with an empty bytes */0.
A 308 naming fewer bytes than were sent re-sends the missing
ones; one that names no progress at all waits the backoff before
re-sending, and gives up as upload_stalled after
max_retries such answers in a row. A 308 naming fewer
bytes than the client already dropped from its buffer cannot be
recovered and is raised at once as upload_range_regressed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
AsyncIterator[bytes]
|
The payload. |
required |
metadata
|
Mapping[str, object]
|
The |
required |
content_type
|
str
|
MIME type of the payload. |
required |
file_id
|
str | None
|
Replace the content of this existing file
( |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
GoogleDriveFile |
GoogleDriveFile
|
The created or updated file. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
On an error answer, when retries run
out, when the session stalls or loses bytes, or when the
session answers |
escape_query_value
¶
Escape a value for a single-quoted string in a Drive q query.
The Drive search syntax
(https://developers.google.com/workspace/drive/api/guides/ref-search-terms)
delimits strings with ' and escapes ' and \ with a
backslash. The backslash is escaped first, so the backslash added in
front of a quote is not doubled again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The raw value. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The value, safe between single quotes. |
auth
¶
Service-account access tokens for the Google Drive API.
A service account authenticates with the OAuth 2.0 JWT bearer grant
(RFC 7523), described by Google in "Using OAuth 2.0 for Server to Server
Applications" (https://developers.google.com/identity/protocols/oauth2/service-account):
the server signs a JWT with the account's private key (RS256), posts it
to the token endpoint and receives a short-lived access token.
No google-auth here: the whole exchange is one signed JWT and one form
post, built on pyjwt + cryptography (both already floors of the
[auth]/[oidc] extras) and httpx.
The token exchange sits behind :class:AccessTokenProvider, so a provider
for a user's OAuth token can replace :class:ServiceAccountTokenProvider
without touching
:class:~tempest_fastapi_sdk.integrations.storage.google_drive.GoogleDriveClient.
GOOGLE_TOKEN_URI
module-attribute
¶
Google's OAuth 2.0 token endpoint, the token_uri of a service-account file.
DRIVE_SCOPE
module-attribute
¶
Full Drive access — what a service account writing into a shared folder needs.
DRIVE_FILE_SCOPE
module-attribute
¶
Per-file Drive access: only files the app created or opened.
JWT_BEARER_GRANT_TYPE
module-attribute
¶
The grant_type of the JWT bearer exchange (RFC 7523, section 2.1).
ASSERTION_LIFETIME_SECONDS
module-attribute
¶
Lifetime of the signed assertion; Google refuses an exp over one hour.
TOKEN_REFRESH_MARGIN_SECONDS
module-attribute
¶
How long before expires_in a cached access token is replaced.
GOOGLE_DRIVE_EXTRA_HINT
module-attribute
¶
GOOGLE_DRIVE_EXTRA_HINT: str = "Google Drive support requires the [google-drive] extra. Install with `pip install tempest-fastapi-sdk[google-drive]`."
Message of the ImportError raised without pyjwt/cryptography.
AccessTokenProvider
¶
Bases: Protocol
Anything that hands out a valid OAuth 2.0 access token for Drive.
:class:ServiceAccountTokenProvider is the implementation shipped
here. A provider for a user's OAuth token (refresh token exchange)
implements the same single method, and
:class:~tempest_fastapi_sdk.integrations.storage.google_drive.GoogleDriveClient
works with it unchanged.
Implementations must be safe to call concurrently and should cache the token until shortly before it expires.
access_token
async
¶
Return a bearer token valid for at least the next request.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The access token, without the |
ServiceAccountCredentials
dataclass
¶
ServiceAccountCredentials(
client_email: str,
private_key: str,
private_key_id: str | None = None,
token_uri: str = GOOGLE_TOKEN_URI,
)
The fields of a service-account JSON key the token exchange needs.
private_key is kept out of repr so the object never prints its
secret, in a traceback or a log line.
Attributes:
| Name | Type | Description |
|---|---|---|
client_email |
str
|
The account's address — the JWT |
private_key |
str
|
The PEM-encoded RSA private key. |
private_key_id |
str | None
|
The key id, sent as the JWT |
token_uri |
str
|
Where the assertion is exchanged; also its |
from_info
classmethod
¶
from_info(info: Mapping[str, object]) -> ServiceAccountCredentials
Build credentials from the parsed service-account JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info
|
Mapping[str, object]
|
The decoded key file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ServiceAccountCredentials |
ServiceAccountCredentials
|
The credentials. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
from_json
classmethod
¶
from_json(text: str) -> ServiceAccountCredentials
Parse a service-account key given inline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The JSON document. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ServiceAccountCredentials |
ServiceAccountCredentials
|
The credentials. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the text is not a JSON object, or the object is not a service-account key. The text is not quoted. |
from_file
classmethod
¶
from_file(path: str | Path) -> ServiceAccountCredentials
Read a service-account key file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the JSON key downloaded from the Google Cloud console. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ServiceAccountCredentials |
ServiceAccountCredentials
|
The credentials. |
Raises:
| Type | Description |
|---|---|
OSError
|
When the file cannot be read. |
ValueError
|
When it is not a service-account key. |
load
classmethod
¶
load(
*, credentials_path: str | Path | None = None, credentials_json: str | None = None
) -> ServiceAccountCredentials
Load credentials from inline JSON or a file — inline JSON wins.
Same precedence as
:class:~tempest_fastapi_sdk.settings.FirebaseSettings: the file is
the usual local shape, the inline JSON is what a deployment without
a mounted volume injects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials_path
|
str | Path | None
|
Path to the key file. |
None
|
credentials_json
|
str | None
|
The key itself. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ServiceAccountCredentials |
ServiceAccountCredentials
|
The credentials. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither source is given, or the one used is not a service-account key. |
OSError
|
When the file cannot be read. |
ServiceAccountTokenProvider
¶
ServiceAccountTokenProvider(
credentials: ServiceAccountCredentials,
*,
http_client: AsyncClient,
scopes: Sequence[str] = (DRIVE_SCOPE,),
refresh_margin_seconds: float = TOKEN_REFRESH_MARGIN_SECONDS,
clock: Callable[[], float] = time,
)
Access tokens from a service account, via the JWT bearer grant.
Each exchange signs a fresh assertion with claims iss
(client_email), scope (space-separated), aud
(token_uri), iat and exp (iat + one hour), RS256,
with kid set to private_key_id. The token is cached until
:data:TOKEN_REFRESH_MARGIN_SECONDS before its expires_in, and an
:class:asyncio.Lock makes concurrent callers share one exchange
instead of each running their own.
Neither the assertion, the private key nor the access token is ever logged or put in an exception message.
Initialize the provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
ServiceAccountCredentials
|
The service account. |
required |
http_client
|
AsyncClient
|
Client used for the token endpoint; the caller owns and closes it. |
required |
scopes
|
Sequence[str]
|
OAuth scopes requested. Defaults to
:data: |
(DRIVE_SCOPE,)
|
refresh_margin_seconds
|
float
|
How long before expiry the cached token is replaced. |
TOKEN_REFRESH_MARGIN_SECONDS
|
clock
|
Callable[[], float]
|
Wall clock in epoch seconds; tests inject a fake. |
time
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
access_token
async
¶
Return a cached token, exchanging a new assertion when it is stale.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The access token. |
Raises:
| Type | Description |
|---|---|
GoogleDriveException
|
When the token endpoint refuses the
assertion ( |
ImportError
|
When the |