4

I have a python script that gets information from a Google Spreedsheet using gspread.

            scope = ['https://spreadsheets.google.com/feeds']
            creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
            client = gspread.authorize(creds)
            sheet_programar = client.open("FILE").worksheet("SHEET")

            # Extract and print all of the values
            list_of_hashes = sheet_programar.get_all_records()

this is part of script that is contatly running, but the gspread part only runns on a few ocations during the day.

this all works, but if i try to use the same credentials on another script to access the same sheet, i get an error that i dont have permision.

My understanding of the problem is that the first script is not closing the connection, hence i can't log in with the same credentials.

i can't find anywhere information on how this can be closed ?

Uniextra
  • 133
  • 3
  • 17

2 Answers2

1

Add this:

client.session.close()
kshishkin
  • 525
  • 5
  • 7
0

There is no function in class Spreadsheet to close a session. Together with the solution from @kshishkin, there are 3 possible ways to 'close' a Google Spreadsheet:

  1. Open the required spreadsheet from within a function. When the function is out of the scope, the spreadsheet object will be closed automatically by Python.

  2. Call del the_googlesheet_obj to delete it google sheet object directly. the_googlesheet_obj is the returned object of the googlesheet.

  3. Call Spreadsheet.client.session.close() object within a the googlesheet object.

Here is an example:

from google.colab import auth
from google.auth import default
import gspread


# Open Google Sheet from within Google Colab
auth.authenticate_user()
gc = gspread.authorize(default()[0])

gs = gc.create('New Googlesheet')  # Create a new Googlesheet document

print(f'{gs.id=}')     # Unique key of the Googlesheet document
print(f'{gs.title=}')  # Title of the Googlesheet document
print(f'{gs.url=}')    # URL of the Googlesheet document

ws = gs.get_worksheet(0)  # Get the first worksheet
ws.update('A1', [[1,2], [3, 4]])  # Update from cell A1

ws.client.session.close()  # Close the session
yoonghm
  • 4,198
  • 1
  • 32
  • 48