【发布时间】:2022-01-28 18:09:02
【问题描述】:
所以我目前可以使用我的社交用户帐户登录,但似乎无法访问该用户的日历 API 事件。 这是一个网络应用,所以下面的代码似乎打开了另一个标签。
流程:登录->主页->日历(localhost:8000/accounts/login-> localhost:8000->localhost:8000/日历)
@login_required
def calendar(request):
context={}
results = get_user_events(request)
context['results'] = results
context['nmenu'] = 'calendar'
return render(request, 'home.html', context)
日历.py
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import os
def get_user_events(request):
creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())
try:
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.')
return
# Prints the start and name of the next 10 events
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
return events
except HttpError as error:
print('An error occurred: %s' % error)
return []
我的 Uris
urls.py:
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('oauth/', include('social_django.urls', namespace='social'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
【问题讨论】:
标签: django google-calendar-api python-social-auth