Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.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 from_db_value()缺少1个必需的位置参数:';上下文';_Python_Django_Google Api Python Client_Oauth2client - Fatal编程技术网

Python from_db_value()缺少1个必需的位置参数:';上下文';

Python from_db_value()缺少1个必需的位置参数:';上下文';,python,django,google-api-python-client,oauth2client,Python,Django,Google Api Python Client,Oauth2client,正在尝试使用GoogleAppClient和oauth2client为django创建google登录 我能够打开主页,并成功重定向到谷歌登录。登录后,它将重定向到我收到此错误的主页 参考文献 视图.py import httplib2 from googleapiclient.discovery import build from django.http import HttpResponseBadRequest from django.http import HttpResponseRed

正在尝试使用
GoogleAppClient
oauth2client
为django创建google登录

我能够打开主页,并成功重定向到谷歌登录。登录后,它将重定向到我收到此错误的主页

参考文献

视图.py

import httplib2

from googleapiclient.discovery import build
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from .models import CredentialsModel
from gfglogin import settings
from oauth2client.contrib import xsrfutil
from oauth2client.client import flow_from_clientsecrets
from oauth2client.contrib.django_util.storage import DjangoORMStorage
from django.shortcuts import render
from httplib2 import Http


def home(request):
    print("*****home*****")
    status = True

    if not request.user.is_authenticated:
        return HttpResponseRedirect('admin')

    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()
    print(f"credential: {credential}")
    print(f"storage: {storage}")

    try:
        access_token = credential.access_token
        resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly",
                                    headers={'Host': 'www.googleapis.com',
                                            'Authorization': access_token})
    except:
        status = False
        print('Not Found')

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


################################
#   GMAIL API IMPLEMENTATION   #
################################

# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which are found
# on the API Access tab on the Google APIs
# Console <http://code.google.com/apis/console>


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:8080/oauth2callback',
    prompt='consent')


def gmail_authenticate(request):
    print("*****gmail_authenticate*****")
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()
    print(f"credential: {credential}")
    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})


def auth_return(request):
    print("*****auth_return*****")
    get_state = bytes(request.GET.get('state'), 'utf8')
    if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
                                   request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    print(f"credential: {credential}")
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    print(f"storage: {storage}")
    print("access_token: %s" % credential.access_token)
    return HttpResponseRedirect("/")
导入httplib2
从GoogleAppClient.discovery导入生成
从django.http导入HttpResponseBadRequest
从django.http导入HttpResponseRedirect
from.models导入凭证model
从gfglogin导入设置
从oauth2client.contrib导入xsrfutil
从oauth2client.client导入流\u从\u clientsecrets
从oauth2client.contrib.django_util.storage导入DjangoORMStorage
从django.shortcuts导入渲染
从httplib2导入Http
def home(请求):
打印(“******主页*****”)
状态=真
如果未对request.user.u进行身份验证:
返回HttpResponseRedirect('admin')
存储=djangormstorage(CredentialsModel,'id',request.user,'credential')
credential=storage.get()
打印(f“凭证:{credential}”)
打印(f“存储:{storage}”)
尝试:
访问令牌=凭证。访问令牌
resp,cont=Http()。请求(“https://www.googleapis.com/auth/gmail.readonly",
headers={'Host':'www.googleapis.com',
“授权”:访问(令牌})
除:
状态=错误
打印('未找到')
返回呈现(请求'index.html',{'status':status})
################################
#GMAIL API实现#
################################
#CLIENT_SECRETS,包含此文件的OAuth 2.0信息的文件名
#应用程序,包括找到的客户端id和客户端机密
#在Google API上的API访问选项卡上
#控制台
流量=来自客户机密的流量(
settings.GOOGLE\u OAUTH2\u CLIENT\u SECRETS\u JSON,
范围=https://www.googleapis.com/auth/gmail.readonly',
重定向http://127.0.0.1:8080/oauth2callback',
立即同意)
def gmail_身份验证(请求):
打印(“****gmail\u验证*******”)
存储=djangormstorage(CredentialsModel,'id',request.user,'credential')
credential=storage.get()
打印(f“凭证:{credential}”)
如果凭证为无或凭证无效:
FLOW.params['state']=xsrfutil.generate_令牌(settings.SECRET_密钥,
请求(用户)
authorize\u url=FLOW.step1\u get\u authorize\u url()
返回HttpResponseRedirect(授权url)
其他:
http=httplib2.http()
http=凭证.授权(http)
service=build('gmail','v1',http=http)
打印('access\u token=',credential.access\u token)
状态=真
返回呈现(请求'index.html',{'status':status})
def认证返回(请求):
打印(“****验证返回******”)
get_state=bytes(request.get.get('state'),'utf8')
如果不是xsrfutil.validate_令牌(settings.SECRET_密钥,get_状态,
请求(用户):
返回HttpResponseBadRequest()
凭证=FLOW.step2_交换(request.GET.GET('code'))
打印(f“凭证:{credential}”)
存储=djangormstorage(CredentialsModel,'id',request.user,'credential')
存储.put(凭证)
打印(f“存储:{storage}”)
打印(“访问令牌:%s”%credential.access\u令牌)
返回HttpResponseRedirect(“/”)
错误:

System check identified no issues (0 silenced).
June 06, 2020 - 14:38:49
Django version 3.0.7, using settings 'gfglogin.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
[06/Jun/2020 14:39:00] "GET /admin/ HTTP/1.1" 200 3042
*****home*****
credential: None
storage: <oauth2client.contrib.django_util.storage.DjangoORMStorage object at 0x0000014A630EABE0>
Not Found
[06/Jun/2020 14:39:05] "GET / HTTP/1.1" 200 327
*****gmail_authenticate*****
credential: None
[06/Jun/2020 14:39:07] "GET /gmailAuthenticate HTTP/1.1" 302 0
*****auth_return*****
credential: <oauth2client.client.OAuth2Credentials object at 0x0000014A6322BA00>
storage: <oauth2client.contrib.django_util.storage.DjangoORMStorage object at 0x0000014A6322B550>
access_token: ya29.a0AfH6SMBLyCWC3cV4iiMk0jWUJaw8ruUFoBqFTkM5LT2acAc6FelcoADU3tn67RslO-24dKEFqrdp4tcLFVuEIMvmn7cHKeb8XeZ9YNQozRoRSTU6hs-jMA9bHP10epw1ImbBaY8SUgQUtF75mRRniR0aELEmzTVKGe8
[06/Jun/2020 14:40:26] "GET /oauth2callback?state=VaASAVe2IusAHCsQfc7EfToxNTkxNDM0NTQ3&code=4/0gFCWPMx4qTUrv4wUWpSKbA8Z_rTaZb-YGGDRrK4NsK2UiW6f4MpA_g1Pr5RpyGcRxbCtWlH6qHvKIJvbpG_L9c&scope=https://www.googleapis.com/auth/gmail.readonly HTTP/1.1" 302 0
*****home*****
Internal Server Error: /
Traceback (most recent call last):
  File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\PERSONAL DATA\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\PERSONAL DATA\raw_login\google-oauth-mail\gfgauth\views.py", line 23, in home
    credential = storage.get()
  File "D:\PERSONAL DATA\env\lib\site-packages\oauth2client\client.py", line 407, in get
    return self.locked_get()
  File "D:\PERSONAL DATA\env\lib\site-packages\oauth2client\contrib\django_util\storage.py", line 58, in locked_get
    if len(entities) > 0:
  File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 258, in __len__
    self._fetch_all()
  File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\query.py", line 74, in __iter__
    for row in compiler.results_iter(results):
  File "D:\PERSONAL DATA\env\lib\site-packages\django\db\models\sql\compiler.py", line 1096, in apply_converters
    value = converter(value, expression, connection)
TypeError: from_db_value() missing 1 required positional argument: 'context'
系统检查未发现任何问题(0静音)。
2020年6月6日14:38:49
Django版本3.0.7,使用设置“gfglogin.settings”
正在启动开发服务器http://127.0.0.1:8080/
使用CTRL-BREAK退出服务器。
[06/Jun/2020 14:39:00]“GET/admin/HTTP/1.1”200 3042
*****家*****
凭证:无
存储:
找不到
[06/Jun/2020 14:39:05]“GET/HTTP/1.1”200 327
*****gmail_认证*****
凭证:无
[06/Jun/2020 14:39:07]“GET/Gmail身份验证HTTP/1.1”302 0
*****验证返回*****
凭据:
存储:
访问令牌:ya29.a0afh6smblycwc3cv4iimk0jwujaw8ruufobqftkm5lt2acc6felcoadu3tn67rslo-24dkefqrdpdp4tclfvmueimn7chkeb8xez9ynqozrorstu6hs-jma9bhp10epw1imbyam8sugqutf75mrn0aelemztvkge8
[06/Jun/2020 14:40:26]“GET/oauth2callback?state=VaASAVe2IusAHCsQfc7EfToxNTkxNDM0NTQ3&code=4/0gfcwpmx4qturv4wwwpskba8z_rTaZb-YGGDRrK4NsK2UiW6f4MpA\u g1pr5rpygcrxbctwl6hvkivbpg\u L9c&scope=https://www.googleapis.com/auth/gmail.readonly HTTP/1.1“302 0
*****家*****
内部服务器错误:/
回溯(最近一次呼叫最后一次):
文件“D:\PERSONAL DATA\env\lib\site packages\django\core\handlers\exception.py”,第34行,在内部
响应=获取响应(请求)
文件“D:\PERSONAL DATA\env\lib\site packages\django\core\handlers\base.py”,第115行,在\u get\u响应中
response=self.process\u异常\u由\u中间件(e,请求)
文件“D:\PERSONAL DATA\env\lib\site packages\django\core\handlers\base.py”,第113行,在\u get\u响应中
响应=包装的回调(请求,*回调参数,**回调参数)
文件“D:\PERSONAL DATA\raw\u login\google oauth mail\gfgauth\views.py”,第23行,在home中
credential=storage.get()
文件“D:\PERSONAL DATA\env\lib\site packages\oauth2client\client.py”,第407行,在get中
返回self.locked_get()
文件“D:\PERSONAL DATA\env\lib\site packages\oauth2client\contrib\django\u util\storage.py”,第58行,在locked\u get中
如果len(实体)>0:
文件“D:\PERSONAL DATA\env\lib\site packages\django\db\models\query.py”,第258行,在__
self._fetch_all()
文件“D:\PERSONAL DATA\env\lib\site packages\django\db\models\query.py”,第1261行,位于“fetch\u all”中
self.\u result\u cache=list(self.\u iterable\u class(self))
文件“D:\PERSONAL DATA\env\lib\site packages\django\db\models\query.py”,第74行,在__
对于编译器中的行。结果\u iter(结果):
文件“D:\PERSONAL DATA\env\lib\site packages\django\db\models\sql\co