简体   繁体   中英

Google Docs API Creating Documents on Python Service is Not Defined

I am trying to create a document on Google Docs API using python, but when I use the script I get this error - NameError: name 'service' is not defined .

This is the script I am using (fromhttps://developers.google.com/docs/api/how-tos/documents#python ):

title = 'My Document'
body = {
    'title': title
}
doc = service.documents() \
    .create(body=body).execute()
print('Created document with title: {0}'.format(
    doc.get('title')))

Any help to fix this would be much appreciated!

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM