Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pathlib
- import google.auth.exceptions
- import google.auth.transport.requests
- from google.oauth2.credentials import Credentials
- from google_auth_oauthlib.flow import InstalledAppFlow
- import requests
- import toml
- CONFIG = toml.load('config.toml')
- def authorize_gsc(save: bool = True):
- """Authorizes access to Google Search Console and returns credentials"""
- secrets_location = pathlib.Path(CONFIG['gsc']['secrets'])
- token_location = pathlib.Path(CONFIG['gsc']['token'])
- # Only attempt to get new credentials if the load fails.
- try:
- creds = Credentials.from_authorized_user_file(token_location)
- request = google.auth.transport.requests.Request()
- creds.refresh(request)
- except (FileNotFoundError, google.auth.exceptions.RefreshError) as e:
- # Run through the OAuth flow and retrieve credentials
- flow = InstalledAppFlow.from_client_secrets_file(secrets_location,
- CONFIG['gsc']['scopes'])
- creds = flow.run_console()
- if save:
- with open(token_location, 'w') as f:
- f.write(creds.to_json())
- return creds
- def inspect_url_manual(url: str, site: str) -> dict:
- creds = authorize_gsc()
- body = {
- 'inspectionUrl': url,
- 'siteUrl': site,
- 'languageCode': 'en-US'
- }
- headers = {'authorization': f'Bearer {creds.token}'}
- res = requests.post('https://searchconsole.googleapis.com/v1/urlInspection/index:inspect',
- json=body,
- headers=headers)
- res.raise_for_status()
- return res.json()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement