此示例 Web 应用会输出您可以访问的网站列表,以及其中每个网站的站点地图(如果有)。
要求
要运行此程序,您需要:
- 互联网和网络浏览器的访问权限,以便向示例应用授权。
- Google 帐号,其中至少一个网站已在 Google Search Console 中通过验证。
- Python 3 和 flask Web 应用框架。
操作说明
在此示例中,您将调整适用于 Web 服务器应用的 OAuth 2.0 示例应用。此示例 Python 应用使用 Flask Web 应用框架来运行基于 Web 的应用,该应用管理 OAuth 密钥并调用 Google Cloud API。您将调整链接的示例以调用 Search Console API 并在网页中输出结果。
按照上方链接的 OAuth 示例页面上的设置说明进行操作,并复制示例代码,然后修改代码,如下所示。具体来说,请按照编码环境的设置说明进行操作,设置(或重复使用)可以访问 Google Cloud 控制台中的 Search Console API 的项目,以及为 Web 应用生成凭据。
您将使用适用于 Python 的完整代码示例作为此示例的源代码。
请阅读下面的修改,了解您需要对链接的说明进行哪些更改。
如果您需要从 Google App Engine 项目访问 Google API Python 客户端,则需要使用服务帐号来管理您的权限。
修改
按照链接的 Oauth2 示例页面上的说明操作时,请进行以下更改:
- 启用 Google Search Console API 而非 Drive 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
在测试中,我们需要在 Bash 环境中将 OAUTHLIB_INSECURE_TRANSPORT 手动设置为 1:
export OAUTHLIB_INSECURE_TRANSPORT=1
。如果您收到有关运行示例应用所需的 HTTPS 的错误,请尝试设置该变量。