Skip to content
Advertisement

Is it possible to pass the google api client object to a function?

I have got the following authentication function:

course_id = "Classexample"
def connect():
    creds = None

    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    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.json', 'w') as token:
            token.write(creds.to_json())

    service = build('classroom', 'v1', credentials=creds)

    return service

and the following Google Classroom function

def teachers_list(course_Id, service):
    lst1 = service.courses().teachers().list(courseId=course_Id).execute()
    lst1 = lst1.get('teachers', [])
    teachers = {}
    for T in lst1:
        teachers[T["userId"]] = T['profile']['emailAddress']

    return teachers

Running it like

print(teachers_list(course_id, connect()))

Whenever I run this, I get error 401, that I don’t have the authentication credential. The problem with this is that I do, and in the case of the program written in only one function, it somehow works. I might end up combining all functions even if it’s messy but I would like to know why this is happening anyway.

Advertisement

Answer

You’re correct in your assumption and your code appears to be fine (and you should try to not mash everything into a single function).

Given your statement, that it works as a single function, I suspect (!?) that what you’re presenting as the code in your question is incorrect.

When you say “Running it like”, is the print statement part of the process, i.e.:

course_id = ...

def connect():
    ...

def teachers_list(course_id, service):
    ...


print(teachers_list(course_id, connect()))

Or perhaps as part of main:

course_id = ...

def connect():
    ...

def teachers_list(course_id, service):
    ...

def main():
    print(teachers_list(course_id, connect()))

if __name__ == '__main__':
    main()

Both of these configurations will (!) work.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement