Google Calendar与Django集成 [英] Google Calendar Integration with Django

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

问题描述

是否有完整的基于Django的Google日历集成示例?我正在阅读 Google的示例页面,但其链接位于底部

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.

由于Google的示例仅着重于如何获取访问令牌,因此我特别在尝试刷新令牌。到目前为止,我就是这样:

I'm specifically struggeling with the refresh token as Google's examples focus solely on how to get the access token. That's what I have so far:

@staff_member_required
def authorize_access(request):
    return redirect(get_flow(request).step1_get_authorize_url())

@staff_member_required
def oauth2_callback(request):
    credentials = get_flow(request).step2_exchange(request.GET['code'])

    store = get_store()
    store.put(credentials)
    credentials.set_store(store)

    return redirect('...')

def get_flow(request):
    flow = client.flow_from_clientsecrets(os.path.join(CREDENTIAL_DIR, CLIENT_SECRET_FILE),
                                      SCOPES,
                                      redirect_uri='%s://%s/google-calendar/oauth2-callback/' % (request.META['wsgi.url_scheme'], request.META['HTTP_HOST'],))
    flow.params['access_type'] = 'offline'
    flow.params['approval_prompt'] = 'force'

    return flow

def get_store():
    return oauth2client.file.Storage(os.path.join(CREDENTIAL_DIR, ACCESS_TOKEN_FILE))

def has_valid_api_credentials():
    credentials = get_store().get()
    return credentials is not None

def build_service():
    credentials = get_store().get()

    if not credentials:
        return None
    elif credentials.access_token_expired:
        http = credentials.refresh(httplib2.Http())
        http = get_store().get().authorize(http)
    else:
        http = credentials.authorize(httplib2.Http())

    service = discovery.build('calendar', 'v3', http=http)

    return service

def create_events(rental_request):
    service = build_service()

    event = service.events().insert(...).execute()


推荐答案

研究了许多不同的方法,我发现服务器到服务器的身份验证是我想要的这样一来,用户无需明确地授予权限,就不必更新获取的身份验证令牌。而是使用服务帐户,服务器可以自行进行呼叫。

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.

在开始编码之前,您必须设置这样的服务帐户并将其添加到日历中,您想要服务帐户访问。 Google在此处。然后,转到 https://calendar.google.com ,在屏幕左侧找到您要查看的日历想要与您的新服务帐户共享,然后单击它旁边的三角形。从下拉菜单中选择日历设置。这将带您进入一个屏幕,在该屏幕上您将找到以后需要的日历ID(将其写下来),并在顶部显示一个标签以共享对日历的访问权限。作为个人,从服务帐户中插入电子邮件地址,为其分配相应的权限,然后单击保存(如果不单击保存,将不会添加服务帐户)。

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='<YOUR EMAIL HERE>@gmail.com', body={
        'summary': 'Foo',
        'description': 'Bar',
        'start': {'dateTime': start_datetime.isoformat()},
        'end': {'dateTime': (start_datetime + timedelta(minutes=15)).isoformat()},
    }).execute()

    print(event)

我正在使用oauth2client版本2.2.0( pip install oauth2client )。

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

我希望这个答案有帮助:)

I hope this answer helps :)

这篇关于Google Calendar与Django集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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