Google 日历与 Django 的集成 [英] Google Calendar Integration with Django

查看:25
本文介绍了Google 日历与 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()

推荐答案

请注意:虽然代码有效,但根据 https://github.com/googleapis/google-auth-library-python/blob/7a8641a7f0718c0dce413436f23691e8590face1/docs/index.rst ,oauth2client 最近已被弃用,取而代之的是 google-auth 库 - https://github.com/googleapis/google-auth-library-python/tree/edfe24602051969e32917e82bcedd2bace43e260

Just a note here: Although the code works, as per https://github.com/googleapis/google-auth-library-python/blob/7a8641a7f0718c0dce413436f23691e8590face1/docs/index.rst, oauth2client has been deprecated recently in favour of google-auth library - https://github.com/googleapis/google-auth-library-python/tree/edfe24602051969e32917e82bcedd2bace43e260

您可以在此处找到新库的文档 - https://google-auth.readthedocs.io/en/latest/user-guide.html

You can find the documentation of the new library here - https://google-auth.readthedocs.io/en/latest/user-guide.html

要使用新的库,代码可以写成

To use the new library, the code can be written as

import datetime
from datetime import timedelta

import pytz

from google.oauth2 import service_account

from googleapiclient.discovery import build

service_account_email = "app-calendar@xxxxxxxxx.iam.gserviceaccount.com"
SCOPES = ["https://www.googleapis.com/auth/calendar"]

credentials = service_account.Credentials.from_service_account_file('google_calendar_credential.json')
scoped_credentials = credentials.with_scopes(SCOPES)


def build_service():
    service = build("calendar", "v3", credentials=scoped_credentials)
    return service


def create_event():
    service = build_service()

    start_datetime = datetime.datetime.now(tz=pytz.utc)
    event = (
        service.events()
        .insert(
            calendarId="primary",
            body={
                "summary": "Foo 2",
                "description": "Bar",
                "start": {"dateTime": start_datetime.isoformat()},
                "end": {
                    "dateTime": (start_datetime + timedelta(minutes=15)).isoformat()
                },
            },
        )
        .execute()
    )

    print(event)

create_event()

由于我没有足够的声誉将此作为评论发布,因此我将其作为单独的帖子发布

As I do not have enough reputation to post this as comment, I am posting this as a separate post

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

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