Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django应用程序中集成Google登录和日历访问_Python_Django_Google Calendar Api_Google Signin - Fatal编程技术网

Python 在Django应用程序中集成Google登录和日历访问

Python 在Django应用程序中集成Google登录和日历访问,python,django,google-calendar-api,google-signin,Python,Django,Google Calendar Api,Google Signin,我正在尝试在Django应用程序中集成Google登录和访问Google日历。我已经使用pythonsocialauth成功地处理了前者 我还根据代码使用googleapi-python-client获得了一个简单的django应用程序,可以访问日历 但我不知道应该如何将它们集成到一个工作流中,这样我就可以在用户登录时获得日历访问权限。如果您能为我提供一些示例代码,我将不胜感激。请尝试。它包括登录和使用该身份验证生成令牌。此令牌将用于执行日历API调用。使用它并添加您自己的代码 下面是一个片段:

我正在尝试在Django应用程序中集成Google登录和访问Google日历。我已经使用
pythonsocialauth
成功地处理了前者

我还根据代码使用
googleapi-python-client
获得了一个简单的django应用程序,可以访问日历

但我不知道应该如何将它们集成到一个工作流中,这样我就可以在用户登录时获得日历访问权限。如果您能为我提供一些示例代码,我将不胜感激。

请尝试。它包括登录和使用该身份验证生成令牌。此令牌将用于执行日历API调用。使用它并添加您自己的代码

下面是一个片段:

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 = oauth2client.file.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

下面是我如何让它工作的:

models.py

from django.db import models
from oauth2client.contrib.django_orm import CredentialsField

class Credentials(models.Model):
    id = models.OneToOneField(User, primary_key=True)
    credential = CredentialsField()

    class Meta:
        db_table = 'credentials'
设置.py

.
.
.
GOOGLE_CLIENT_ID = ''  
GOOGLE_CLIENT_SECRET = ''
GOOGLE_SCOPE = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar'
OAUTH_REDIRECT_URI = 'http://<domain>/oauth2/redirect/'
.
.
.

您是用代码替换python social auth还是将两者结合使用?我没有使用python social auth。我甚至无法让它运行。当我尝试
manage.py migrate
时,我得到了
importorror:没有名为django\u orm的模块。也许会有帮助?
import httplib2
from django.conf import settings
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.http import (HttpResponse, HttpResponseBadRequest,
                         HttpResponseRedirect)
from django.shortcuts import redirect
from oauth2client.contrib import xsrfutil
from oauth2client.contrib.django_orm import Storage

from .models import Credentials


def get_flow(request):    
    flow = OAuth2WebServerFlow(
        client_id=settings.GOOGLE_CLIENT_ID,
        client_secret=settings.GOOGLE_CLIENT_SECRET,
        scope=settings.GOOGLE_SCOPE,
        redirect_uri=settings.OAUTH_REDIRECT_URI,
        access_type='offline',
        state=''
    )
    return flow


def login(request):
    next = request.GET.get('next', 'home')
    request.session['next'] = next

    if not request.user.is_authenticated():
        flow = get_flow(request)
        flow.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                       request.user)
        request.session['flow'] = pickle.dumps(flow).decode('iso-8859-1')
        redirect_uri = flow.step1_get_authorize_url()
        return redirect(redirect_uri)
    else:
        return redirect(reverse_lazy(next))


def oauth2redirect(request):
    # Make sure that the request is from who we think it is
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.GET.get('state').encode('utf8'),
                                   request.user):
        return HttpResponseBadRequest()

    code = request.GET.get('code')
    error = request.GET.get('error')

    if code:
        flow = get_flow(request)
        credentials = flow.step2_exchange(code)

        request.session['creds'] = credentials.to_json()
        email = credentials.id_token.get("email")
        user_exists = False
        try:
            user = User.objects.get(email=email)
            user_exists = True
        except User.DoesNotExist:
            user = create_user(credentials)

        # Since we've oauth2'd the user, we should set the backend appropriately
        # This is usually done by the authenticate() method.
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        # Refresh token is needed for renewing google api access token
        if credentials.refresh_token:
            user.refresh_token = credentials.refresh_token
        user.save()

        storage = Storage(Credentials, 'id', user, 'credential')
        storage.put(credentials)

        # Register that the user has successfully logged in
        auth_login(request, user)

        next = request.session.get('next', reverse_lazy('/'))
        return HttpResponseRedirect(next)
    elif code is None and error:
        return HttpResponse(str(error))
    else:
        return HttpResponseBadRequest()


@login_required
def logout(request):
    user = request.user
    credentials = Credentials.objects.get(id=user.id)
    credentials.revoke(httplib2.Http())
    credentials.delete()
    storage = Storage(Credentials, 'id', user, 'credential')
    storage.delete()

    auth_logout(request)
    return HttpResponseRedirect('/')