pythonauthenticationgoogle-sheetspdfoauth-2.0

Export a Google Sheet to PDF file with Python requests


Recently I have been trying to convert a Google Sheet into a PDF file, by retaining all formatting data. From my previous question, I have gotten a solution to request https://docs.google.com/spreadsheets/d/...id.../export?format=pdf. Replace ...id..., as @doubleunary mentioned.

This is how I am constructing the link.

URL = "https://docs.google.com/spreadsheets/d/"
ID = "1ZUG5Xlesc-e1EfGg_T16vamQ_igMXvPb6VNQoWZegDE"

PARAM = [
    '/export?exportFormat=pdf&format=pdf',
    '&size=LETTER',
    '&portrait=true',
    '&fitw=true',
    '&top_margin=0.75',
    '&bottom_margin=0.75',
    '&left_margin=0.7',
    '&right_margin=0.7',
    '&sheetnames=false&printtitle=false',
    '&pagenum=UNDEFINED',
    '&gridlines=true',
    '&fzr=FALSE'
]

params = ''
for param in PARAM:
    params += param

CALL = URL + ID + params

Now, I have encountered the problem of authentication. I don't want to give view access to anyone with the link either. Below is the code I've used for OAuth2, but I don't know how I can use the authentication to post a request.

    from requests_oauthlib import OAuth2Session
    import os
    os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = ' '

    client_id = xxx
    client_secret = xxx
    redirect_uri = 'http://localhost'

    scope = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
    oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
    authorization_url, state = oauth.authorization_url(
        "https://accounts.google.com/o/oauth2/auth",
        access_type="offline",
        prompt="select_account")

    print(f'Please go to {authorization_url} and authorize access.')
    authorization_response = input('Enter the full callback URL - ')

    token = oauth.fetch_token(
            "https://oauth2.googleapis.com/token",
            code=authorization_response,
            client_secret=client_secret)

    r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')

    for i in r:
        print(i)

The code returns the correct user details, but when I try request.get(CALL) after authentication, it still returns a 401 code. How can I put the authentication to use?

I want to avoid things like Selenium, because they often result in Captcha problems.


Solution

  • Your can send the token as query parameter. Append to PARAM before joining:

    PARAM.append(f"&access_token={token}")
    

    And as Lime Husky commented, you need appropriate scopes, specifically,

    https://www.googleapis.com/auth/spreadsheets
    

    Or

    https://www.googleapis.com/auth/drive