このサンプル ウェブアプリは、アクセス可能なサイトのリストと、各サイトのサイトマップ(存在する場合)を出力します。
要件
このプログラムを実行するには、以下が必要です。
- サンプルアプリを承認するためのインターネット アクセスとウェブブラウザ。
- 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 サンプルページの手順に沿って操作する場合は、次の変更を行います。
- Drive API ではなく Google Search Console API を有効にします。
上記のリンク先の 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'
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
Google のテストでは、Bash 環境(
export OAUTHLIB_INSECURE_TRANSPORT=1
)で OAUTHLIB_INSECURE_TRANSPORT を手動で 1 に設定する必要がありました。サンプルアプリの実行に必要な HTTPS に関するエラーが発生した場合は、その変数を設定してみてください。