You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python实现Google OAuth后获取用户邮箱遇端口占用问题

解决OAuth认证时「Address already in use」端口占用问题

问题原因

报错OSError: [Errno 98] Address already in use是因为run_local_server()默认使用的8080端口被其他进程占用,或是第一次认证后端口未正常释放,导致第二次启动本地服务器失败。

解决方案

1. 指定自定义端口

直接在run_local_server()方法中指定一个未被占用的端口,比如8081:

flow.run_local_server(port=8081)

这样每次运行都会使用你指定的端口,避开默认8080可能存在的占用问题。

2. 释放被占用的默认端口

如果坚持使用默认的8080端口,先找到并杀掉占用该端口的进程:

  • Linux/macOS:
    终端执行命令找到进程PID:
    lsof -i :8080
    
    然后杀掉对应进程(替换<PID>为实际进程号):
    kill <PID>
    
  • Windows:
    命令提示符执行命令找到PID:
    netstat -ano | findstr :8080
    
    强制终止进程:
    taskkill /PID <PID> /F
    

3. 优化认证流程,复用已保存的凭据

第一次认证后,Google会默认生成token.json保存凭据。修改代码直接加载该文件,避免重复启动本地服务器,从根源解决端口问题:

from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import os
from googleapiclient.discovery import build

def get_user_info():
    creds = None
    # 加载已保存的凭据
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json')
    
    # 处理凭据过期或无效的情况
    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.json',
                scopes=['openid',
                        'https://www.googleapis.com/auth/userinfo.email',
                        'https://www.googleapis.com/auth/userinfo.profile'])
            flow.run_local_server(port=8081)
            creds = flow.credentials
        # 保存凭据供下次使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    
    user_info_service = build('oauth2', 'v2', credentials=creds)
    user_info = user_info_service.userinfo().get().execute()
    return user_info['email']

修改后,第二次运行会直接读取已有的token.json,无需再次启动本地服务器,彻底避免端口冲突。


内容的提问来源于stack exchange,提问作者Jakob Czapski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:25:17