Google calender API入门 [英] Google calender API getting started

查看:75
本文介绍了Google calender API入门的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试熟悉Google Calendar API.在入门指南中,他们有以下代码示例:

I'm trying to get familiar with the google calendar api. In the getting started guide they have this code example:

from __future__ import print_function
import datetime
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/calendar.readonly']


def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])


if __name__ == '__main__':
    main()

在此示例中,如果我们尚未通过pickle文件进行访问,我们将自动打开一个窗口,要求用户访问其日历.问题是我不希望该窗口自动打开,我想打印一个链接,而不是用户可以单击以进行身份​​验证.我在文档中四处张望,但似乎找不到任何有用的东西.我会向我求助,谢谢!

In this example we automatically open a window to ask the user to access their calendar, if we don't already have access through the pickle file. The thing is I don't want this window to open automatically, I want to print a link instead that the user can click to authenticate. I have looked around in the documentation but can't seem to find anything usefull. I would appriciate any help i could get, thanks!

推荐答案

  • 对于授权过程,您只想显示URL.您不想自动打开浏览器.
  • 您要使用带有python的googleapis实现此目的.
  • 如果我的理解是正确的,那么这个答案如何?请认为这只是几个可能的答案之一.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    在这种情况下,请使用 Flow.from_client_secrets_file 而不是 InstalledAppFlow.from_client_secrets_file .

    In this case, please use Flow.from_client_secrets_file instead of InstalledAppFlow.from_client_secrets_file.

    修改脚本后,请进行以下修改.

    When your script is modified, please modify as follows.

    from google_auth_oauthlib.flow import InstalledAppFlow
    

    收件人:

    来自google_auth_oauthlib.flow的

    To:

    from google_auth_oauthlib.flow import Flow
    

    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('calendar', 'v3', credentials=creds)
    

    收件人:

    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:
            # Create the flow using the client secrets file from the Google API
            # Console.
            flow = Flow.from_client_secrets_file('client_secret.json', SCOPES, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
            # Tell the user to go to the authorization URL.
            auth_url, _ = flow.authorization_url(prompt='consent')
    
            print('Please go to this URL: {}'.format(auth_url))
    
            # The user will get an authorization code. This code is used to get the
            # access token.
            code = input('Enter the authorization code: ')
            flow.fetch_token(code=code)
            creds = flow.credentials
    
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    
    service = build('calendar', 'v3', credentials=creds)
    

    • 在这种情况下,当您在 token.pickle 下运行脚本时,授权的URL将显示在控制台上.浏览器未打开.因此,请通过打开浏览器访问URL并授权范围.然后,请将复制的授权码到控制台,然后输入Enter键.这样,将检索访问令牌并创建 token.pickle 文件.
      • In this case, when you run the script under token.pickle is not existing, the URL for the authorization is displayed to the console. The browser is not opened. So please access to the URL by opening the browser and authorize the scopes. Then, please the copied authorization code to the console and input enter key. By this, the access token is retrieved and the file of token.pickle is created.
        • 如果发生与重定向uri相关的错误,请将其修改为 http://localhost 并再次进行测试.
        • If an error related to the redirect uri occurs, please modify it to http://localhost and test it again.

        如果我误解了你的问题,而这不是你想要的方向,我深表歉意.

        If I misunderstood your question and this was not the direction you want, I apologize.

          我在上面的示例脚本中提出了
        • 我想打印一个链接,而不是用户可以单击以对您的问题进行身份验证.
        • 某种不手动确认授权码的方式中,我认为上述示例脚本不合适.
        • From I want to print a link instead that the user can click to authenticate in your question, I proposed above sample script.
        • From some way not to manually confirm authorization codes in your replying, I think that that above sample script is not suitable.

        在这种情况下,如何使用服务帐户?使用服务帐户时,不需要授权码.使用服务帐户的脚本如下.

        In this case, how about using the service account? When the service account is used, no authorization code is required. The script for using the service account is as follows.

        from google.oauth2 import service_account
        from googleapiclient.discovery import build
        
        SERVICE_ACCOUNT_FILE = 'service-account-credentials.json'  # Here, please set the creadential file of the service account.
        SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
        creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
        
        service = build('calendar', 'v3', credentials=creds)
        

        注意:

        • 为了使用服务帐户访问Google日历,请首先与服务帐户的电子邮件共享Google日历.请注意这一点.
        • 这篇关于Google calender API入门的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆