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 ?

3
  • 1
    Did you find a solution? I have the same problem. Commented Sep 29, 2018 at 18:18
  • 1
    Still no solution to this problem? Commented Nov 27, 2018 at 15:47
  • Gapread does not maintain an open connection. I creates a new connection each time you make a request. Your issue is somewhere else 😉 Commented Apr 7, 2022 at 13:34

2 Answers 2

1

Add this:

client.session.close()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.