Bắt đầu nhanh: Chạy ứng dụng Search Console bằng Python

Ứng dụng web mẫu này in danh sách trang web mà bạn có thể truy cập và sơ đồ trang web, nếu có, cho từng trang web đó.

Yêu cầu

Để chạy chương trình này, bạn cần có:

  • Truy cập vào Internet và trình duyệt web để cấp quyền cho ứng dụng mẫu.
  • Tài khoản Google có ít nhất một trang web đã xác minh trong Google Search Console.
  • Python 3 và khung ứng dụng web flask.

Hướng dẫn

Đối với mẫu này, bạn sẽ điều chỉnh OAuth 2.0 cho mẫu Ứng dụng máy chủ web COM+. Ứng dụng python mẫu này sử dụng khung ứng dụng web flask để chạy một ứng dụng dựa trên nền tảng web quản lý khoá OAuth và gọi một Google Cloud API. Bạn sẽ điều chỉnh mẫu được liên kết để gọi API Search Console và xuất ra kết quả tìm kiếm trong một trang web.

Làm theo hướng dẫn thiết lập trên trang mẫu OAuth được liên kết ở trên rồi sao chép mã mẫu, sau đó sửa đổi mã như dưới đây. Cụ thể, hãy làm theo hướng dẫn thiết lập môi trường lập trình, thiết lập (hoặc tái sử dụng) dự án có thể truy cập vào API Search Console trong bảng điều khiển Google Cloud và tạo thông tin đăng nhập cho một ứng dụng web.

Bạn sẽ sử dụng Ví dụ về mã hoàn chỉnh cho Python làm mã nguồn cho mẫu này.

Đọc phần Sửa đổi bên dưới để biết những thay đổi bạn cần thực hiện với .

Nếu bạn cần truy cập vào Ứng dụng Google API Python từ một Google App Engine dự án của bạn, bạn sẽ cần sử dụng tài khoản dịch vụ để quản lý quyền của bạn.

Sửa đổi

Khi làm theo hướng dẫn trên trang mẫu Oauth2 được liên kết, hãy thực hiện những thay đổi sau:

  1. Bật API Google Search Console thay vì API Drive.
  2. Sao chép đơn đăng ký mẫu ở cuối tài liệu OAUth được liên kết ở trên, và thay thế đoạn mã này

    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
    API_SERVICE_NAME = 'drive'
    API_VERSION = 'v2'
    
    Bằng cách này:
    SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']
    API_SERVICE_NAME = 'searchconsole'
    API_VERSION = 'v1'
    

  3. Thay thế nội dung của ngôn ngữ Python test_api_request() bằng mã sau:

    @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. Trong quá trình thử nghiệm, chúng tôi cần thiết lập OAUTHLIB_INSECURE_TRANSPORT theo cách thủ công thành 1 trong môi trường Bash: export OAUTHLIB_INSECURE_TRANSPORT=1. Nếu bạn gặp lỗi về yêu cầu giao thức HTTPS để chạy ứng dụng mẫu, hãy thử đặt biến.