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

无需设置环境变量,如何在Python程序中配置GCP服务账号密钥?

无需手动设置环境变量的Google Cloud Vision OCR认证方案

我正在用Google Cloud Vision OCR替代Pytesseract,Google官方建议通过设置GOOGLE_APPLICATION_CREDENTIALS环境变量指向密钥文件完成认证——在VSCode的PowerShell里执行$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\User_1\key.json"能正常工作,但程序要给老板用,总不能让他每次都跑这个命令。而且最后会用pyinstaller打包成独立exe,用Python执行PowerShell命令的方案也不可行。

Google提供的环境变量验证代码如下:

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

implicit()

我知道Google Sheets API有这样的认证代码:

def auth():
            creds = None
            token_file = 'token.json'
            SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']
            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='credentials.json', scopes=SCOPES)
                    creds = flow.run_local_server(port=0)
                with open(token_file, 'w') as token:
                    token.write(creds.to_json())
            return creds

但不确定这套方案是否适用于Cloud Vision场景,想知道除了手动执行命令外,还有哪些可行的认证方式。


可行的替代认证方案

1. 代码中直接加载密钥文件

这是最便捷的方式,无需依赖环境变量。初始化Cloud Vision客户端时,直接传入密钥文件路径即可:

from google.cloud import vision_v1

def init_vision_client():
    # 打包exe时,把key.json和exe放在同一目录即可
    client = vision_v1.ImageAnnotatorClient.from_service_account_json('key.json')
    return client

# 使用示例
client = init_vision_client()
# 后续正常调用OCR接口

打包完成后,只需让老板把密钥文件和exe放在同一个文件夹,程序就能自动读取密钥,无需额外操作。

2. 将密钥嵌入exe内部(更安全)

如果不想暴露密钥文件,可以用pyinstaller的资源嵌入功能,把key.json打包进exe:

  1. 创建.spec文件并添加资源配置:
a = Analysis(...)
# 把key.json嵌入到exe,运行时会自动提取到临时目录
a.datas += [('key.json', 'C:\\实际路径\\key.json', 'DATA')]
pyz = PYZ(a.pure, a.zipped_data, cipher=None)
exe = EXE(...)
  1. 代码中处理嵌入的资源路径:
import os
import sys
from google.cloud import vision_v1

def get_resource_path(relative_path):
    # 适配pyinstaller打包后的路径逻辑
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

def init_vision_client():
    key_path = get_resource_path('key.json')
    client = vision_v1.ImageAnnotatorClient.from_service_account_json(key_path)
    return client

这样生成的exe是完全独立的,不需要额外携带密钥文件,安全性更高。

3. 关于Google Sheets认证方式的说明

你提到的Sheets API代码用的是OAuth 2.0授权码流程,这种方式需要用户手动登录Google账号授权,适合访问用户个人Google资源的场景(比如用户自己的Sheets文档)。而Cloud Vision OCR属于服务端API,用服务账号密钥认证即可,不需要用户授权,因此Sheets的这套流程不适用于当前场景,直接加载服务账号密钥是更合适的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:18:13