Advertisement
joejoinerr

Python: Manually call GSC URL inspection API

Feb 1st, 2022 (edited)
749
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import pathlib
  2.  
  3. import google.auth.exceptions
  4. import google.auth.transport.requests
  5. from google.oauth2.credentials import Credentials
  6. from google_auth_oauthlib.flow import InstalledAppFlow
  7. import requests
  8. import toml
  9.  
  10.  
  11. CONFIG = toml.load('config.toml')
  12.  
  13.  
  14. def authorize_gsc(save: bool = True):
  15.     """Authorizes access to Google Search Console and returns credentials"""
  16.     secrets_location = pathlib.Path(CONFIG['gsc']['secrets'])
  17.     token_location = pathlib.Path(CONFIG['gsc']['token'])
  18.    
  19.     # Only attempt to get new credentials if the load fails.
  20.     try:
  21.         creds = Credentials.from_authorized_user_file(token_location)
  22.         request = google.auth.transport.requests.Request()
  23.         creds.refresh(request)
  24.     except (FileNotFoundError, google.auth.exceptions.RefreshError) as e:
  25.         # Run through the OAuth flow and retrieve credentials
  26.         flow = InstalledAppFlow.from_client_secrets_file(secrets_location,
  27.                                                          CONFIG['gsc']['scopes'])
  28.         creds = flow.run_console()
  29.  
  30.     if save:
  31.         with open(token_location, 'w') as f:
  32.             f.write(creds.to_json())
  33.    
  34.     return creds
  35.  
  36.  
  37. def inspect_url_manual(url: str, site: str) -> dict:
  38.     creds = authorize_gsc()
  39.    
  40.     body = {
  41.         'inspectionUrl': url,
  42.         'siteUrl': site,
  43.         'languageCode': 'en-US'
  44.     }
  45.     headers = {'authorization': f'Bearer {creds.token}'}
  46.    
  47.     res = requests.post('https://searchconsole.googleapis.com/v1/urlInspection/index:inspect',
  48.                         json=body,
  49.                         headers=headers)
  50.     res.raise_for_status()
  51.    
  52.     return res.json()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement