Home > OS >  Replit error with google API but works in Pycharm
Replit error with google API but works in Pycharm

Time:09-23

I was following this tutorial: replit error

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

CodePudding user response:

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)

  • Related