需要在 python 的帮助下在我的谷歌驱动器上创建应用程序。但是VS显示错误。
运行后出现:刷新凭据时出错:“NoneType”对象没有属性“刷新” 请访问此网址以授权此应用程序:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=228094037930-l00h64amkuagnntu0kamq46ib2d115fo.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A50240% 2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets.readonly&state=QOGYtOBVWbUPl2iLCKIWP1F25fobuh&access_type=offline
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
# The ID and range of a sample spreadsheet.
SPREADSHEET_ID = "1AaPqHjJirTTyBW2n30bKUuFlTD7meXix3WS1oJXe1pQ"
RANGE_NAME = "Class Data!A2:E"
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
try:
creds.refresh(Request())
except Exception as e:
print(f"Error refreshing credentials: {e}")
if not creds or not creds.valid:
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
credential_file = os.path.join(CURR_DIR, 'credentials.json')
flow = InstalledAppFlow.from_client_secrets_file(credential_file, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
service = build("sheets", "v4", credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId="1AaPqHjJirTTyBW2n30bKUuFlTD7meXix3WS1oJXe1pQ", range="Class Data!A2:E").execute()
values = result.get("values", [])
if not values:
print("No data found.")
return
print("Name, Major:")
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print(f"{row[0]}, {row[4]}")
except HttpError as err:
print(f"HTTP error: {err}")
if __name__ == "__main__":
main()