How to use the gspread.exceptions.WorksheetNotFound function in gspread

To help you get started, we’ve selected a few gspread examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github robin900 / gspread-dataframe / tests / gspread_dataframe_integration.py View on Github external
def setUpClass(cls):
        super(WorksheetTest, cls).setUpClass()
        ss_id = cls.config.get('Spreadsheet', 'id')
        cls.spreadsheet = cls.gc.open_by_key(ss_id)
        try:
            test_sheet = cls.spreadsheet.worksheet('wksht_int_test')
            if test_sheet:
                # somehow left over from interrupted test, remove.
                cls.spreadsheet.del_worksheet(test_sheet)
        except gspread.exceptions.WorksheetNotFound:
            pass # expected
github dataiku / dataiku-contrib / googlesheets / python-connectors / googlesheets-sheet / connector.py View on Github external
def get_spreadsheet(self):

        try:
            return self.gspread_client.open_by_key(self.doc_id).worksheet(self.tab_id)
        except gspread.exceptions.SpreadsheetNotFound as e:
            raise Exception("Trying to open non-existent or inaccessible spreadsheet document.")
        except gspread.exceptions.WorksheetNotFound as e:
            raise Exception("Trying to open non-existent sheet. Verify that the sheet name exists (%s)." % self.tab_id)
        except gspread.exceptions.APIError as e:
            if hasattr(e, 'response'):
                error_json = e.response.json()
                print(error_json)
                error_status = error_json.get("error", {}).get("status")
                email = self.credentials.get("client_email", "(email missing)")
                if error_status == 'PERMISSION_DENIED':
                    raise Exception("The Service Account does not have permission to read or write on the spreadsheet document. Have you shared the spreadsheet with %s?" % email)
                if error_status == 'NOT_FOUND':
                    raise Exception("Trying to open non-existent spreadsheet document. Verify the document id exists (%s)." % self.doc_id)
            raise Exception("The Google API returned an error: %s" % e)
github dataiku / dataiku-contrib / googlesheets / python-lib / googlesheets.py View on Github external
* credentials
    * doc_id
    * tab_id
    Returns a gspread's worksheet object.
    """
    credentials = get_credentials(credentials)
    scope = [
        'https://www.googleapis.com/auth/spreadsheets'
    ]
    gspread_client = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_dict(credentials, scope))

    try:
        return gspread_client.open_by_key(doc_id).worksheet(tab_id)
    except gspread.exceptions.SpreadsheetNotFound as e:
        raise Exception("Trying to open non-existent or inaccessible spreadsheet document.")
    except gspread.exceptions.WorksheetNotFound as e:
        raise Exception("Trying to open non-existent sheet. Verify that the sheet name exists (%s)." % tab_id)
    except gspread.exceptions.APIError as e:
        if hasattr(e, 'response'):
            error_json = e.response.json()
            print(error_json)
            error_status = error_json.get("error", {}).get("status")
            email = credentials.get("client_email", "(email missing)")
            if error_status == 'PERMISSION_DENIED':
                error_message = error_json.get("error", {}).get("message", "")
                raise Exception("Access was denied with the following error: %s. Have you enabled the Sheets API? Have you shared the spreadsheet with %s?" % (error_message, email))
            if error_status == 'NOT_FOUND':
                raise Exception("Trying to open non-existent spreadsheet document. Verify the document id exists (%s)." % doc_id)
        raise Exception("The Google API returned an error: %s" % e)
github aiguofer / gspread-pandas / gspread_pandas / spread.py View on Github external
-------
        None
        """
        self.sheet = None
        if isinstance(sheet, int):
            if sheet >= len(self.sheets) or sheet < -1 * len(self.sheets):
                raise WorksheetNotFound("Invalid sheet index {}".format(sheet))
            self.sheet = self.sheets[sheet]
        else:
            self.sheet = self.find_sheet(sheet)

        if not self.sheet:
            if create:
                self.create_sheet(sheet)
            else:
                raise WorksheetNotFound("Worksheet not found")
github trebortech / hoolie / custom_modules / engines / gspread.py View on Github external
for docid in documentids:

        # Open the spreadsheet by the id
        odoc = gc.open_by_key(docid)

        # Get the first worksheet
        wks = odoc.get_worksheet(0)

        # Get the first line as the values for keys
        titlerow = filter(None, wks.row_values(1))

        # Get worksheet that engine data to find what row last processed
        try:
            dbdoc = odoc.worksheet(adminsheet)
            lastrow = dbdoc.acell('A1').value
        except WorksheetNotFound:
            dbdoc = odoc.add_worksheet(adminsheet, 1, 1)
            dbdoc.update_acell('A1', '1')
            lastrow = '1'

        nextlineid = int(lastrow) + 1
        lineloop = True
        while lineloop:
            nextline = filter(None, wks.row_values(nextlineid))
            evtdata = {'doctitle': odoc.title,
                       'docid': odoc.id,
                       'data': {}}
            outdata = {}
            if nextline:
                outdata = dict(zip(titlerow, nextline))
                evtdata['data'] = outdata
                # Send event
github burnash / gspread / gspread / models.py View on Github external
Example. Getting worksheet named 'Annual bonuses'

        >>> sht = client.open('Sample one')
        >>> worksheet = sht.worksheet('Annual bonuses')

        """
        sheet_data = self.fetch_sheet_metadata()
        try:
            item = finditem(
                lambda x: x['properties']['title'] == title,
                sheet_data['sheets']
            )
            return Worksheet(self, item['properties'])
        except (StopIteration, KeyError):
            raise WorksheetNotFound(title)
github trebortech / hoolie / custom_modules / runners / gspread.py View on Github external
for docid in documentids:
        
        # Open the spreadsheet by the id
        odoc = gc.open_by_key(docid)

        # Get the first worksheet
        wks = odoc.get_worksheet(0)

        # Get the first line as the values for keys
        titlerow = filter(None, wks.row_values(1))

        # Get worksheet that engine data to find what row last processed
        try:
            dbdoc = odoc.worksheet(adminsheet)
            lastrow = dbdoc.acell('A1').value
        except WorksheetNotFound:
            dbdoc = odoc.add_worksheet(adminsheet, 1, 1)
            dbdoc.update_acell('A1', '1')
            lastrow = '1'

        nextlineid = int(lastrow) + 1
        lineloop = True
        while lineloop:
            nextline = filter(None, wks.row_values(nextlineid))
            evtdata = {'doctitle': odoc.title,
                       'docid': odoc.id,
                       'data': {}}
            outdata = {}
            if nextline:
                outdata = dict(zip(titlerow, nextline))
                evtdata['data'] = outdata
                # Send event
github aiguofer / gspread-pandas / gspread_pandas / spread.py View on Github external
----------
        sheet : str,int,Worksheet
            name, index, or Worksheet object
        create : bool
            whether to create the sheet if it doesn't exist,
            see :meth:`create_sheet `
            (default False)

        Returns
        -------
        None
        """
        self.sheet = None
        if isinstance(sheet, int):
            if sheet >= len(self.sheets) or sheet < -1 * len(self.sheets):
                raise WorksheetNotFound("Invalid sheet index {}".format(sheet))
            self.sheet = self.sheets[sheet]
        else:
            self.sheet = self.find_sheet(sheet)

        if not self.sheet:
            if create:
                self.create_sheet(sheet)
            else:
                raise WorksheetNotFound("Worksheet not found")
github burnash / gspread / gspread / v4 / models.py View on Github external
Example. Getting worksheet named 'Annual bonuses'

        >>> sht = client.open('Sample one')
        >>> worksheet = sht.worksheet('Annual bonuses')

        """
        sheet_data = self.fetch_sheet_metadata()
        try:
            item = finditem(
                lambda x: x['properties']['title'] == title,
                sheet_data['sheets']
            )
            return Worksheet(self, item['properties'])
        except (StopIteration, KeyError):
            raise WorksheetNotFound(title)