Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Worksheet ID Type Inconsistencies #1269

Merged
merged 9 commits into from
Aug 13, 2023
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
22 changes: 16 additions & 6 deletions gspread/spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""

import warnings
from typing import Union

from .exceptions import WorksheetNotFound
from .urls import (
Expand Down Expand Up @@ -270,11 +271,11 @@ def get_worksheet(self, index):
except (KeyError, IndexError):
raise WorksheetNotFound("index {} not found".format(index))

def get_worksheet_by_id(self, id):
def get_worksheet_by_id(self, id: Union[str, int]):
"""Returns a worksheet with specified `worksheet id`.

:param id: The id of a worksheet. it can be seen in the url as the value of the parameter 'gid'.
:type id: int
:type id: str | int

:returns: an instance of :class:`gspread.worksheet.Worksheet`.
:raises:
Expand All @@ -287,14 +288,19 @@ def get_worksheet_by_id(self, id):
"""
sheet_data = self.fetch_sheet_metadata()

try:
worksheet_id_int = int(id)
except ValueError as ex:
raise ValueError("id should be int") from ex

try:
item = finditem(
lambda x: x["properties"]["sheetId"] == id,
lambda x: x["properties"]["sheetId"] == worksheet_id_int,
sheet_data["sheets"],
)
return Worksheet(self, item["properties"])
except (StopIteration, KeyError):
raise WorksheetNotFound("id {} not found".format(id))
raise WorksheetNotFound("id {} not found".format(worksheet_id_int))

def worksheets(self, exclude_hidden: bool = False):
"""Returns a list of all :class:`worksheets <gspread.worksheet.Worksheet>`
Expand Down Expand Up @@ -439,12 +445,16 @@ def del_worksheet(self, worksheet):

return self.batch_update(body)

def del_worksheet_by_id(self, worksheet_id: str):
def del_worksheet_by_id(self, worksheet_id: Union[str, int]):
"""
Deletes a Worksheet by id
"""
try:
worksheet_id_int = int(worksheet_id)
except ValueError as ex:
raise ValueError("id should be int") from ex

body = {"requests": [{"deleteSheet": {"sheetId": worksheet_id}}]}
body = {"requests": [{"deleteSheet": {"sheetId": worksheet_id_int}}]}

return self.batch_update(body)

Expand Down
Loading
Loading