gpt4 book ai didi

python - 获取访问 token 后如何读取用户的谷歌日历事件?

转载 作者:行者123 更新时间:2023-12-04 13:40:35 26 4
gpt4 key购买 nike

我想在 django 中获取我的用户的谷歌日历事件,我编写了以下代码。此代码有效并保存用户的访问 token ,但我不知道我应该怎么做才能在它之后获取用户的谷歌日历事件。
在此之前我遇到了一些问题,并在 this question 中询问了它并试图解决它,现在我在这里。
有人能帮我吗?

在网址中:

url(r'^new_event/$', views.new_event, name="new_event"),
url(r'^oauth2_callback', OAuth2CallBack.as_view(), name='oauth2_callback'),
url(r'^access_to_google_calendar$', views.access_to_google_calendar,
name="access_to_google_calendar"),

鉴于:
def access_to_google_calendar(request):
# Following line is for getting google calendar events of user to show him
flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR,
settings.CLIENT_SECRET_CALENDAR,
scope='https://www.googleapis.com/auth/calendar',
redirect_uri=settings.REDIRECT_URI_CALENDAR)
generated_url = flow.step1_get_authorize_url()
return HttpResponseRedirect(generated_url)



class OAuth2CallBack(View):
def get(self, request, *args, **kwargs):
code = request.GET.get('code', False)
if not code:
return JsonResponse({'status': 'error, no access key received from Google or User declined permission!'})

flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR, settings.CLIENT_SECRET_CALENDAR,
scope='https://www.googleapis.com/auth/calendar',
redirect_uri=settings.REDIRECT_URI_CALENDAR)
credentials = flow.step2_exchange(code)

http = httplib2.Http()
http = credentials.authorize(http)

credentials_js = json.loads(credentials.to_json())
access_token = credentials_js['access_token']
# Store the access token in case we need it again!
username = request.user.username
with open('token.csv', 'w') as file:
fieldnames = ['user', 'token']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'user': username, 'token': access_token})

request.session['access_token'] = access_token
return redirect('new_event')

def post(self, request, *args, **kwargs):
return HttpResponseNotAllowed('Only GET requests!')



def new_event(request):
# Here how to get google event of user?????

最佳答案

我终于找到了如何创建服务来获取谷歌日历事件 只有访问 token :

首先你应该得到之前保存的 token (来自csv文件或数据库或......这里保存在csv文件中)

token = get_from_any_where_you_saved_it_before

然后:(在这种情况下,第一行很重要)
credentials = client.AccessTokenCredentials(token, 'USER_AGENT')
service = build('calendar', 'v3', credentials=credentials)
google_calendar_events = service.events().list(calendarId='primary', singleEvents=True,
orderBy='startTime').execute()
google_calendar_events = google_calendar_events.get('items', [])

关于python - 获取访问 token 后如何读取用户的谷歌日历事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com