I posted this as a comment but I might as well have it be an answer, since I found the issue.
The issue is that you can't just run that code alone and expect anything to work. From looking around the API documentation you copied that code from (here), it's clear that you didn't start with the Python Quickstart page, which has an example script that sets up the service
variable among other things. Once you use that code to define and set up service
, the code from your example should work as expected.
Here's an example of what I meant - just took the example, pasted it here, and pasted in the code that you were trying to run below the comment # Create a document called 'My Document'
:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/documents.readonly']
# The ID of a sample document.
DOCUMENT_ID = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE'
def main():
"""Shows basic usage of the Docs API.
Prints the title of a sample document.
"""
creds = None
# The file token.pickle 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.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('docs', 'v1', credentials=creds)
# Create a document called 'My Document'
title = 'My Document'
body = { 'title': title }
doc = service.documents().create(body=body).execute()
print('Created document with title: {0}'.format(doc.get('title')))
if __name__ == '__main__':
main()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…