Search code examples
pythonapidrive

Replit error with google API but works in Pycharm


I was following this tutorial: https://developers.google.com/drive/api/v3/quickstart/python#trouble I followed every step (has some trouble with creating credentials but got it working) but at the last step, it gave me an error. At Step 3.2 it says "a. Click Accept. The app is authorized to access your data." if I run the same script through pycharm (an IDE for python) everything works fine and when I log in I get a message on chrome saying "everything worked You can close this webpage". But if I do it in replit after I log in it give me this error: replit error

If someone can help me that would be helpful! (I'm a beginner at api's so please be patient with me)


Solution

  • So the issue is with the redirect back after the login. As you can see from the error message the localhost (see wiki) refused the connection. This is very much expected behavior as it's not the local machine running the code, but you're running it in the cloud when using replit.

    The code sample you're using cannot be used directly using replit. What you can do is run the code locally once to create the token file and upload that to replit. Note that this solution is not advised, but I'm including it for your understanding.

    The specific code section I'm talking about is:

            # Save the credentials for the next run
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    

    This part creates a token.json file after the login flow. If this file exists then the login flow is not used, as per this section of code:

        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    

    Actual solution

    The better solution is to replace the code below:

                creds = flow.run_local_server(port=0)
    

    with the code below:

                creds = flow.run_console()
    

    as described in the documentation for the library here.

    What this does is to print out a link which you need to visit in another browser window. It has more or less the same login flow as the flow.run_local_server(port=0) but instead of redirecting to localhost it generates a code which you need to paste in replit. It should be reasonably obvious to do and is meant for issues like the one you're experiencing.

    This method can be used for example when you're remoted into a cloud machine that only has commandline. (fe. headless computer)