我在 python 3 和 django 3 中有以下代码。我在 API 中记录了所有以前的 google api 步骤,当我运行我的服务器时,我可以完成这个过程并获得一个凭证 access_token,但是当我尝试使用它时它失败了当我尝试执行对业务 API 方法的请求时。
from django.http import HttpResponseRedirect,
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import google_auth_oauthlib.flow
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import GoogleCredentialsModel
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
SCOPES = ['https://www.googleapis.com/auth/business.manage',]
@xframe_options_exempt
def auth_request(request):
user = User.objects.get(id=request.user.id) # request.user
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS,
SCOPES,
)
flow.redirect_uri = settings.GOOGLE_BUSINESS_CALLBACK
authoritation_url, state = flow.authorization_url(
# # Enable offline access so that you can refresh an access token without
# # re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# # Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true',
# # ask always if consent
prompt='consent'
)
return HttpResponseRedirect(authoritation_url)
@xframe_options_exempt
def auth_return(request):
state = request.GET["state"]
code = request.GET["code"]
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS,
SCOPES,
state=state)
flow.redirect_uri = settings.GOOGLE_BUSINESS_CALLBACK
try:
flow.fetch_token(code=code)
user = request.user
user = TSMUser.objects.get(id=user.id)
if GoogleCredentialModel.objects.filter(user=user).exists():
gcred = GoogleCredentialModel.objects.get(user=user)
gcred.set_data(Credentials(**flow.credentials))
else:
GoogleCredentialModel.objects.create(user=user,
credential=Credentials(**flow.credentials))
service = build('business', 'v4', discoveryServiceUrl='https://developers.google.com/my-business/samples/mybusiness_google_rest_v4p5.json', credentials=flow.credentials)
list = service.accounts().list().execute()
# Previous line returns <HttpError 404 when requesting https://mybusiness.googleapis.com/v4/accounts?alt=json returned "Method not found.">
except:
pass
return render('google_business.html', {'business_list': list.json()})
但是我无法在 python 3 中解决或找到此错误的解决方案我搜索的每个站点我都使用 python2、oauth2client 和 httplib2 找到旧版本的文档
在此链接中是使用 python 2 和 oauth2client 的示例: https ://github.com/googleapis/google-api-python-client