此示例 Web 应用会输出您可以访问的网站列表,以及站点地图、 (如果有的话)。
要运行此程序,您需要:
在此示例中,您将调整适用于 Web 服务器应用的 OAuth 2.0 示例 应用。 此示例 Python 应用使用 Flask Web 应用框架来 基于网络的应用,用于管理 OAuth 密钥和调用 Google Cloud API。您 将调整链接的示例以调用 Search Console API,并打印 生成网页。
按照上方链接的 OAuth 示例页面上的设置说明进行操作,并将 示例代码,然后修改代码,如下所示。具体来说,请遵循 针对编码环境、设置(或重复使用)项目的设置说明 可访问 Google Cloud 控制台中的 Search Console API,以及生成凭据 用于 Web 应用。
您将使用完整代码示例 Python 作为此示例的源代码。
请阅读下面的修改,了解您需要对链接到的链接进行哪些更改 操作说明。
如果您需要从 Google App Engine 访问 Google API Python 客户端 则需要使用一个服务账号 以管理您的权限。
按照链接的 OAuth2 示例页面中的说明操作时, 进行如下更改:
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 resultsexport OAUTHLIB_INSECURE_TRANSPORT=1。 如果您收到有关运行示例应用所需的 HTTPS 的错误,请尝试设置 变量。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。