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

이 샘플 웹 앱은 액세스할 수 있는 사이트 목록과 해당되는 경우 노출수에 변동이 생길 수 있습니다.

요구사항

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

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

안내

이 샘플의 경우 웹 서버 애플리케이션용 OAuth 2.0 샘플 애플리케이션입니다. 이 샘플 Python 앱은 flask 웹 애플리케이션 프레임워크를 사용하여 OAuth 키를 관리하고 Google Cloud API를 호출하는 웹 기반 애플리케이션입니다. 나 Search Console API를 호출하도록 링크된 샘플을 조정하고 웹페이지일 수도 있습니다.

위에 링크된 OAuth 샘플 페이지의 설정 안내를 따른 다음 그런 다음 아래와 같이 코드를 수정하세요. 특히 코딩 환경을 위한 설정 안내, 프로젝트 설정 (또는 재사용) 사용자 인증 정보를 생성하여 웹 애플리케이션을 위한 것입니다

이 코드에서는 전체 코드 예시사용해 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. 테스트에서 OAUTHLIB_INSECURE_TRANSPORT를 수동으로 Bash 환경에서는 1로 변경됨: export OAUTHLIB_INSECURE_TRANSPORT=1 샘플 앱을 실행하는 데 필요한 HTTPS에 대한 오류가 발생하면 변수의 값을 지정합니다.