【问题标题】:NameError at /gmailAuthenticate/ NameError: name 'xsrfutil' is not defined/gmailAuthenticate/ NameError 处的 NameError:未定义名称“xsrfutil”
【发布时间】:2019-10-20 07:37:52
【问题描述】:

我希望该网站的访问者通过 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})

网址.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'),
]

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

【问题讨论】:

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


    【解决方案1】:

    看起来 xsrfutil 是 outh2client.contrib 的一部分。你没有导入它。将其添加到:

    from oauth2client.client import flow_from_clientsecrets, xsrfutil
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 2021-04-15
        • 2019-01-26
        • 2021-10-05
        • 2017-08-16
        相关资源
        最近更新 更多