由于错误 400/WinError 10048 错误,Google Drive API 将无法在开发服务器中运行

问题描述 投票:0回答:1

我正在将 Google Drive API 集成到 Flask 应用程序中,但在开发服务器中本地测试它时遇到问题。

这是代码,来自 这些 Google 文档:

SCOPES = ['https://www.googleapis.com/auth/drive']
CLIENT_SECRETS_FILE = 'credentials.json'
TOKEN_FILE = 'token.json'

def upload_file():
    creds = None

    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    
    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(CLIENT_SECRETS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)

        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

(为简洁起见,未包含导入和后续 Google Drive 上传代码)

问题是,当我在上面的动态端口上运行它时,我收到此错误,因为它选择的随机端口未在 GCloud 中注册:

错误 400:redirect_uri_mismatch

当我将端口更改为在 GCloud 中注册的端口(例如 8080)时,它会出现以下错误:

OSError: [WinError 10048] 通常只允许每个套接字地址(协议/网络地址/端口)使用一次

有什么方法可以在开发服务器中测试它还是我必须部署它?

我根据 Google 文档建立了 Google Drive API,验证了我的凭据.json 与 GCloud 中的信息匹配,并使用此函数尝试将 .docx 上传到 Google Drive。我期望它上传文档,但在这一行出错了:

creds = flow.run_local_server(port=0)
python google-drive-api
1个回答
0
投票

Flask 适用于 Web 应用程序。您对已安装应用程序的使用代码因此称为术语

InstalledAppFlow

@app.route('/authorize')
def authorize():
    # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES)

    # The URI created here must exactly match one of the authorized redirect URIs
    # for the OAuth 2.0 client, which you configured in the API Console. If this
    # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
    # error.
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline')

    # Store the state so the callback can verify the auth server response.
    flask.session['state'] = state

    return flask.redirect(authorization_url)
© www.soinside.com 2019 - 2024. All rights reserved.