Google Calendar Integration with Django

后端 未结 3 888
不知归路
不知归路 2020-12-29 15:09

Is there a fully fledged Django-based example of a Google Calendar integration? I was reading through Google\'s example page but their link at the bottom is outdated.

<
3条回答
  •  -上瘾入骨i
    2020-12-29 15:23

    Researching a lot of different approaches I found out that server-to-server authentication is what I wanted. This way no user has to explicitly give permissions and acquired auth-tokens don't have to be renewed. Instead, using a service account, a server can make calls itself.

    Before you can start coding, you have to setup such a service account and add it to your calendar that you want the service account to access. Google has written down the three steps to create an account here. Afterwards, go to https://calendar.google.com, locate on the left side of the screen the calendar you want to share with your new service account and click the triangle next to it. From the drop-down menu choose calendar settings. This takes you to a screen where you'll find the calendar-ID which you'll need later (so write it down) and also displays a tab at the top to share access to the calendar. As "person" insert the email address from the service account, give it the respective permissions and click save (if you don't click save the service account won't be added).

    The code for this is actually pretty elegant:

    import os
    from datetime import timedelta
    import datetime
    import pytz
    
    import httplib2
    from googleapiclient.discovery import build
    from oauth2client.service_account import ServiceAccountCredentials
    
    service_account_email = 'XXX@YYY.iam.gserviceaccount.com'
    
    CLIENT_SECRET_FILE = 'creds.p12'
    
    SCOPES = 'https://www.googleapis.com/auth/calendar'
    scopes = [SCOPES]
    
    def build_service():
        credentials = ServiceAccountCredentials.from_p12_keyfile(
            service_account_email=service_account_email,
            filename=CLIENT_SECRET_FILE,
            scopes=SCOPES
        )
    
        http = credentials.authorize(httplib2.Http())
    
        service = build('calendar', 'v3', http=http)
    
        return service
    
    
    def create_event():
        service = build_service()
    
        start_datetime = datetime.datetime.now(tz=pytz.utc)
        event = service.events().insert(calendarId='@gmail.com', body={
            'summary': 'Foo',
            'description': 'Bar',
            'start': {'dateTime': start_datetime.isoformat()},
            'end': {'dateTime': (start_datetime + timedelta(minutes=15)).isoformat()},
        }).execute()
    
        print(event)
    

    I'm using oauth2client version 2.2.0 (pip install oauth2client).

    I hope this answer helps :)

提交回复
热议问题