尝试为YouTube API运行Flask应用程序:authlib.oauth2.rfc6749.errors.InvalidClientError:(invalid_client)未经授权

时间:2019-04-11 21:19:41

标签: python-3.x youtube-api youtube-data-api

我正在尝试连接到我的Web应用程序,并在通过localhost加载后收到内部服务器错误。

import json

import flask
import httplib2

from apiclient import discovery
from oauth2client import client


app = flask.Flask(__name__)


@app.route('/')
def index():
  if 'credentials' not in flask.session:
    return flask.redirect(flask.url_for('oauth2callback'))
  credentials = client.OAuth2Credentials.from_json(flask.session['credentials'])
  if credentials.access_token_expired:
    return flask.redirect(flask.url_for('oauth2callback'))
  else:
    http_auth = credentials.authorize(httplib2.Http())
    youtube = discovery.build('youtubeAnalytics', 'v1', http_auth)
    report = youtube.reports().query(ids='channel==MINE', start_date='2019-03-01', end_date='2019-03-20', metrics='views').execute()
    return json.dumps(report)


@app.route('/oauth2callback')
def oauth2callback():
  flow = client.flow_from_clientsecrets(
      'client_secrets.json',
      scope='https://www.googleapis.com/auth/yt-analytics.readonly',
      redirect_uri=flask.url_for('oauth2callback', _external=True),
      include_granted_scopes=True)
  if 'code' not in flask.request.args:
    auth_uri = flow.step1_get_authorize_url()
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    credentials = flow.step2_exchange(auth_code)
    flask.session['credentials'] = credentials.to_json()
    return flask.redirect(flask.url_for('index'))


if __name__ == '__main__':
  import uuid
  app.secret_key = str(uuid.uuid4())
  app.debug = False
  app.run()

我的client_secret文件位于当前目录中,并且所有内容均为最新,但是我仍然继续遇到此问题。

1 个答案:

答案 0 :(得分:0)

您做错的事情可能是将位置传递到以下位置的文件client_secrets.json中的方式:

client.flow_from_clientsecrets('client_secrets.json')

尝试将其更改为:

client.flow_from_clientsecrets('/path/of/current/folder/client_secrets.json')

要获取当前目录,可以使用getcwd()方法