Skip to content

Commit

Permalink
Merge pull request #1384 from burnash/bugfix/allow_external_session
Browse files Browse the repository at this point in the history
Allow client to use external Session object
  • Loading branch information
lavigne958 authored Jan 29, 2024
2 parents 617a63f + 963097e commit a14470e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
15 changes: 13 additions & 2 deletions gspread/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from google.oauth2.credentials import Credentials as OAuthCredentials
from google.oauth2.service_account import Credentials as SACredentials
from google_auth_oauthlib.flow import InstalledAppFlow
from requests import Session

from .client import Client
from .http_client import HTTPClient, HTTPClientType
Expand Down Expand Up @@ -54,19 +55,29 @@ def get_config_dir(


def authorize(
credentials: Credentials, http_client: HTTPClientType = HTTPClient
credentials: Credentials,
http_client: HTTPClientType = HTTPClient,
session: Optional[Session] = None,
) -> Client:
"""Login to Google API using OAuth2 credentials.
This is a shortcut/helper function which
instantiates a client using `http_client`.
By default :class:`gspread.HTTPClient` is used (but could also use
:class:`gspread.BackOffHTTPClient` to avoid rate limiting).
It can take an additional `requests.Session` object in order to provide
you own session object.
.. note::
When providing your own `requests.Session` object,
use the value `None` as `credentials`.
:returns: An instance of the class produced by `http_client`.
:rtype: :class:`gspread.client.Client`
"""

return Client(auth=credentials, http_client=http_client)
return Client(auth=credentials, http_client=http_client, session=session)


def local_server_flow(
Expand Down
9 changes: 6 additions & 3 deletions gspread/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from typing import Any, Dict, List, Optional, Tuple, Union

from google.auth.credentials import Credentials
from requests import Response
from requests import Response, Session

from .exceptions import APIError, SpreadsheetNotFound, UnSupportedExportFormat
from .http_client import HTTPClient, HTTPClientType, ParamsType
Expand All @@ -36,9 +36,12 @@ class Client:
"""

def __init__(
self, auth: Credentials, http_client: HTTPClientType = HTTPClient
self,
auth: Credentials,
http_client: HTTPClientType = HTTPClient,
session: Optional[Session] = None,
) -> None:
self.http_client = http_client(auth)
self.http_client = http_client(auth, session)

def get_file_drive_metadata(self, id: str) -> Any:
"""Get the metadata from the Drive API for a specific file
Expand Down

0 comments on commit a14470e

Please sign in to comment.