クイックスタート: Python で Search Console アプリを実行する

このサンプル ウェブアプリは、アクセス可能なサイトのリストと、各サイトのサイトマップ(存在する場合)を出力します。

要件

このプログラムを実行するには、以下が必要です。

  • サンプルアプリを承認するためのインターネットとウェブブラウザへのアクセス。
  • Google Search Console で所有権が証明されている 1 つ以上のウェブサイトがある Google アカウント
  • Python 3 と flask ウェブ アプリケーション フレームワーク。

手順

このサンプルでは、OAuth 2.0 for Web Server Applications サンプル アプリケーションを改良します。このサンプル Python アプリは、Flask ウェブ アプリケーション フレームワークを使用して、OAuth キーを管理し、Google Cloud API を呼び出すウェブベースのアプリケーションを実行します。リンク先のサンプルを変更して Search Console API を呼び出し、結果をウェブページに出力します。

上記のリンク先の OAuth サンプルページにある設定手順に沿って、サンプルコードをコピーしてから、次のようにコードを変更します。具体的には、コーディング環境の設定手順に沿って、Google Cloud コンソールで Search Console API にアクセスできるプロジェクトを設定(または再利用)して、ウェブ アプリケーションの認証情報を生成します。

このサンプルのソースコードとして、Python完全なコードサンプルを使用します。

以下の変更を読み、リンク先の手順に必要な変更を確認してください。

Google App Engine プロジェクトから Google API Python クライアントにアクセスする必要がある場合は、サービス アカウントを使用して権限を管理する必要があります。

改造

リンクされている OAuth2 サンプルページの手順に沿って操作する場合は、次の変更を行います。

  1. Drive API ではなく Google Search Console API を有効にします。
  2. 上記のリンク先の OAUth ドキュメントの最後にあるサンプル アプリケーションをコピーして、

    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
    API_SERVICE_NAME = 'drive'
    API_VERSION = 'v2'
    
    を次のように置き換えます。
    SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
    API_SERVICE_NAME = 'searchconsole'
    API_VERSION = 'v1'
    

  3. Python 言語の test_api_request() 関数の本文を次のコードに置き換えます。

    @app.route('/test')
    def test_api_request():
      if 'credentials' not in flask.session:
        return flask.redirect('authorize')
    
      # Load credentials from the session.
      credentials = google.oauth2.credentials.Credentials(
          **flask.session['credentials'])
    
      # Retrieve list of properties in account
      search_console_service = googleapiclient.discovery.build(
          API_SERVICE_NAME, API_VERSION, credentials=credentials)
      site_list = search_console_service.sites().list().execute()
    
      # Filter for verified URL-prefix websites.
      verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                            if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'].startswith('http')]
    
      # Print the sitemaps for all websites that you can access.
      results = '<!DOCTYPE html><html><body><table><tr><th>Verified site</th><th>Sitemaps</th></tr>'
      for site_url in verified_sites_urls:
    
        # Retrieve list of sitemaps submitted
        sitemaps = search_console_service.sitemaps().list(siteUrl=site_url).execute()
        results += '<tr><td>%s</td>' % (site_url)
    
        # Add a row with the site and the list of sitemaps
        if 'sitemap' in sitemaps:
          sitemap_list = "<br />".join([s['path'] for s in sitemaps['sitemap']])
        else:
          sitemap_list = "<i>None</i>"
        results += '<td>%s</td></tr>' % (sitemap_list)
    
      results += '</table></body></html>'
    
      # Save credentials back to session in case access token was refreshed.
      # ACTION ITEM: In a production app, you likely want to save these
      #              credentials in a persistent database instead.
      flask.session['credentials'] = credentials_to_dict(credentials)
    
      return results
    
    

  4. このテストでは、Bash 環境 export OAUTHLIB_INSECURE_TRANSPORT=1 で OAUTHLIB_INSECURE_TRANSPORT を手動で 1 に設定する必要がありました。サンプルアプリの実行に必要な HTTPS に関するエラーが発生した場合は、その変数を設定してみてください。