빠른 시작: Python에서 Search Console 앱 실행

이 샘플 웹 앱은 액세스할 수 있는 사이트 목록과 각 사이트의 사이트맵(있는 경우)을 출력합니다.

요구사항

이 프로그램을 실행하려면 다음이 필요합니다.

  • 샘플 앱을 승인하기 위한 인터넷 및 웹브라우저 액세스
  • Google Search Console에서 하나 이상의 웹사이트가 확인된 Google 계정.
  • Python 3 및 flask 웹 애플리케이션 프레임워크

안내

이 샘플에서는 웹 서버 애플리케이션용 OAuth 2.0 샘플 애플리케이션을 조정합니다. 이 샘플 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. 위에 링크된 OAUth 문서 끝부분에 있는 샘플 애플리케이션을 복사하고

    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. 테스트에서는 Bash 환경(export OAUTHLIB_INSECURE_TRANSPORT=1)에서 수동으로 OAUTHLIB_INSECURE_TRANSPORT를 1로 설정해야 했습니다. 샘플 앱을 실행하는 데 필요한 HTTPS에 관한 오류가 발생하면 해당 변수를 설정해 보세요.