我使用django-allauth登录用户并查看他们的日历,我希望能够添加约会。
我使用以下代码,它或多或少是来自quickstart.py的剪切和粘贴:
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from apiclient.discovery import build
import datetime
from django.shortcuts import render
try:
import argparse
flags = tools.argparser.parse_args([])
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar'
CLIENT_SECRET_FILE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/cal/client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def set_appointment(request):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
CAL = discovery.build('calendar', 'v3', http=http)
GMT_OFF = '+00:00' # PDT/MST/GMT-7
EVENT = {
'summary': 'Dinner with friends',
'start': {'dateTime': '2016-11-04T19:00:00%s' % GMT_OFF},
'end': {'dateTime': '2016-11-04T22:00:00%s' % GMT_OFF},
#'attendees': [
# {'email': 'friend1@outlook.com'},
# {'email': 'friend2@hotmail.com'},
#],
}
e = CAL.events().insert(calendarId='primary',
sendNotifications=True, body=EVENT).execute()
return render(request, 'cal/index.html')
但是在尝试添加事件时出现以下错误:
<HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json&sendNotifications=true returned "Insufficient Permission">
我想也许改变django-allauth的SCOPE可以解决问题并将其添加到settings.py
SOCIALACCOUNT_PROVIDERS = \
{ 'google':
{ 'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/calendar'],
'AUTH_PARAMS': { 'access_type': 'online' } }}
它不起作用。非常感谢帮助。