クイックスタート: 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. 上記のリンク先の OAU ドキュメントの末尾にあるサンプル アプリケーションをコピーします。 これを

    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. このテストでは、OAUTHLIB_INSECURE_TRANSPORT を手動で設定する必要がありました。 Bash 環境(export OAUTHLIB_INSECURE_TRANSPORT=1)では 1 になります。 サンプルアプリの実行に必要な HTTPS に関するエラーが表示された場合は、次のように設定してみてください。 変数です。