How to run python script with the same port

流过昼夜 提交于 2021-01-28 08:08:03

问题


Right now I am setting up oauth2 from Gmail to send mail from my python script.

I am using a quick start code from Google to verify the authorize code but I am facing a situation where the port always changes when I am running the python script.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                '../credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

if __name__ == '__main__':
    main()

My problem with this code is that whenever I run the script, it always changes the port and I cannot set the redirected URI in google console.

My question is that how can I set the running port on python script?


回答1:


For example, how about the following modification?

From:

creds = flow.run_local_server(port=0)

To:

creds = flow.run_local_server()
  • In this case, the port 8080 is used every time.

or

creds = flow.run_local_server(port=8000)
  • In this case, the port 8000 is used every time.

Reference:

  • run_local_server


来源:https://stackoverflow.com/questions/63393334/how-to-run-python-script-with-the-same-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!