/ gmailAuthenticate / NameError处的NameError:未定义名称'xsrfutil'

时间:2019-06-04 18:37:42

标签: django django-rest-framework django-views

我希望此网站的访问者通过Gmail API进行身份验证。

在views.py的第24行(在FLOW.params ['state']行)获取以下错误:

NameError at /gmailAuthenticate/
name 'xsrfutil' is not defined

Views.py文件:

from django.shortcuts import render
from .models import CredentialsModel
import httplib2
import requests
from oauth2client.client import flow_from_clientsecrets
from gfglogin import settings
from django.http import HttpResponseRedirect
from oauth2client.contrib.django_util.storage import DjangoORMStorage
from oauth2client.contrib.django_util.models import CredentialsField
# Create your views here.

FLOW = flow_from_clientsecrets(
    settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
    scope='https://www.googleapis.com/auth/gmail.readonly',
    redirect_uri='http://127.0.0.1:8000/oauth2callback',
    prompt='consent')

def gmail_authenticate(request):
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()

    if credential is None or credential.invalid:

        FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                            request.user)
        authorize_url = FLOW.step1_get_authorize_url()
        return HttpResponseRedirect(authorize_url)
    else:
        http = httplib2.Http()
        http = credential.authorize(http)
        service = build('gmail', 'v1', http = http)
        print('access_token = ', credential.access_token)
        status = True

        return render(request, 'index.html', {'status': status})

Urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^gmailAuthenticate/', views.gmail_authenticate, name ='gmail_authenticate'),
    url(r'^oauth2callback/', views.auth_return),
    url(r'^$', views.home, name ='home'),
]

无法理解可能是什么原因。

2 个答案:

答案 0 :(得分:0)

xsrfutil似乎是outh2client.contrib的一部分。您没有导入它。将其添加到:

from oauth2client.client import flow_from_clientsecrets, xsrfutil

答案 1 :(得分:0)

您没有导入xsrfutil。您需要通过添加导入 from oauth2client.contrib import xsrfutil

这是文档oauth2client.contrib.xsrfutil module 的链接。