【问题标题】:Can't get calendar api events from user无法从用户那里获取日历 API 事件
【发布时间】: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


    【解决方案1】:

    重定向 URI 未匹配是常见的 oauth 错误。这是您希望将授权返回到的位置。必须在谷歌云控制台注册

    根据您发送的错误消息http://localhost:someport/

    这必须与您在谷歌云控制台中为您的项目添加的项目之一完全匹配,但您似乎没有列出该项目。

    解决方案是从错误消息中获取uri并添加它。请记住,它必须完全匹配,这意味着端口和您的尾随 /。如果您的应用在每次运行时都更改端口,则需要修复它,使其从静态端口运行,以便您可以将其添加为重定向 uri。

    如果您不知道如何解决此问题,此视频将向您展示如何解决。 Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

    【讨论】:

    • 在授权重定向 URI 中添加新 uri 时,它会增加一个新的。所以它是redirect_uri:localhost:61606redirect_uri:localhost:61612
    • 奇怪的是,每次点击 localhost:8000/calendar 都会导致错误,我不确定如何修复它的 uri。
    • 同样,这是一个不同的 URI,这是重定向 url,它不是 localhost 8000,您的应用程序在此运行,这是不同的
    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多