YouTube API-尝试获取频道成员

时间:2020-05-24 18:26:27

标签: python google-api youtube-data-api google-api-python-client

我目前正在尝试编写Python脚本,以使用YouTube API来获取我的YouTube频道成员。我已经创建了一个OAuth客户端,并经过了必要的步骤来设置我的所有令牌(我认为)。当我使用此OAuth客户端获取我的频道的订阅列表和其他信息时,此OAuth客户端有效,但是当我尝试获取我的成员时,我收到403错误。我相信这是因为Members Documention指出我必须填写特定的form才能访问此API路由。我填写了我认为Google需要的所有信息。但是,我没有收到有关此批准状态的任何更新,也没有收到有关是否填写正确信息的指示。

是否有人对使用YouTube API来获取频道成员有任何经验,并且到目前为止我是否做得正确?如果我正确执行此操作,批准一个应用程序需要多长时间才能访问成员API路由?

对于代码,我只是使用Python Web Client Quickstart Guide。我也尝试过使用示波器,但没有成功...

import os
import flask
import requests

import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery

CLIENT_SECRETS_FILE = "client_secret.json"

SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

app = flask.Flask(__name__)
app.secret_key = '5f24ef3cf326d03'


@app.route('/')
def index():
  return print_index_table()


@app.route('/test')
def test_api_request():
  if 'credentials' not in flask.session:
    return flask.redirect('authorize')

  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  youtube = googleapiclient.discovery.build(
      API_SERVICE_NAME, API_VERSION, credentials=credentials)

  # THIS WORKS
  # subs = youtube.subscriptions().list(
  #     part="snippet,contentDetails",
  #     mine=True
  # ).execute()

  # THIS DOESNT WORK
  subs = youtube.members().list(
      part="snippet",
      maxResults=50
  ).execute()

  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.jsonify(**subs)


@app.route('/authorize')
def authorize():
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)

  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  authorization_url, state = flow.authorization_url(
      access_type='offline',
      include_granted_scopes='true')

  flask.session['state'] = state

  return flask.redirect(authorization_url)


@app.route('/oauth2callback')
def oauth2callback():
  state = flask.session['state']

  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  authorization_response = flask.request.url
  flow.fetch_token(authorization_response=authorization_response)

  credentials = flow.credentials
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.redirect(flask.url_for('test_api_request'))


@app.route('/revoke')
def revoke():
  if 'credentials' not in flask.session:
    return ('You need to <a href="/authorize">authorize</a> before ' +
            'testing the code to revoke credentials.')

  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  revoke = requests.post('https://oauth2.googleapis.com/revoke',
                         params={'token': credentials.token},
                         headers={'content-type': 'application/x-www-form-urlencoded'})

  status_code = getattr(revoke, 'status_code')
  if status_code == 200:
    return('Credentials successfully revoked.' + print_index_table())
  else:
    return('An error occurred.' + print_index_table())


@app.route('/clear')
def clear_credentials():
  if 'credentials' in flask.session:
    del flask.session['credentials']
  return ('Credentials have been cleared.<br><br>' +
          print_index_table())


def credentials_to_dict(credentials):
  return {'token': credentials.token,
          'refresh_token': credentials.refresh_token,
          'token_uri': credentials.token_uri,
          'client_id': credentials.client_id,
          'client_secret': credentials.client_secret,
          'scopes': credentials.scopes}


def print_index_table():
  return ('<table>' +
          '<tr><td><a href="/test">Test an API request</a></td>' +
          '<td>Submit an API request and see a formatted JSON response. ' +
          '    Go through the authorization flow if there are no stored ' +
          '    credentials for the user.</td></tr>' +
          '<tr><td><a href="/authorize">Test the auth flow directly</a></td>' +
          '<td>Go directly to the authorization flow. If there are stored ' +
          '    credentials, you still might not be prompted to reauthorize ' +
          '    the application.</td></tr>' +
          '<tr><td><a href="/revoke">Revoke current credentials</a></td>' +
          '<td>Revoke the access token associated with the current user ' +
          '    session. After revoking credentials, if you go to the test ' +
          '    page, you should see an <code>invalid_grant</code> error.' +
          '</td></tr>' +
          '<tr><td><a href="/clear">Clear Flask session credentials</a></td>' +
          '<td>Clear the access token currently stored in the user session. ' +
          '    After clearing the token, if you <a href="/test">test the ' +
          '    API request</a> again, you should go back to the auth flow.' +
          '</td></tr></table>')


if __name__ == '__main__':
  # When running locally, disable OAuthlib's HTTPs verification.
  # ACTION ITEM for developers:
  #     When running in production *do not* leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  app.run('localhost', 8080, debug=True)

具体来说,这些是当前有效的部分(我所属的频道)和不可用的部分(我的频道成员)...

  # THIS WORKS
  # subs = youtube.subscriptions().list(
  #     part="snippet,contentDetails",
  #     mine=True
  # ).execute()

  # THIS DOESNT WORK
  subs = youtube.members().list(
      part="snippet",
      maxResults=50
  ).execute()

0 个答案:

没有答案