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

Linux下Python Gemini API项目:如何实现API密钥持久化存储?

Gemini API密钥持久化配置方案

一、Python自动写入Shell持久化环境变量

可以通过Python自动识别用户的Shell类型,将API密钥写入对应的配置文件(如.bashrc/.zshrc),实现一次输入永久生效:

  1. 先判断用户当前使用的Shell及对应配置文件:
import os

def get_shell_config_path():
    shell_name = os.path.basename(os.environ.get('SHELL', 'bash'))
    config_map = {
        'bash': os.path.expanduser('~/.bashrc'),
        'zsh': os.path.expanduser('~/.zshrc'),
        'fish': os.path.expanduser('~/.config/fish/config.fish')
    }
    return config_map.get(shell_name, os.path.expanduser('~/.bashrc'))
  1. 接收用户输入并写入配置文件:
def setup_persistent_api_key():
    api_key = input("请输入你的Gemini API密钥: ").strip()
    if not api_key:
        print("密钥不能为空,请重新输入")
        return
    
    config_file = get_shell_config_path()
    env_line = f'export GEMINI_API_KEY="{api_key}"'

    # 检查是否已存在该环境变量
    with open(config_file, 'r') as f:
        for line in f.readlines():
            if line.strip().startswith('export GEMINI_API_KEY='):
                print("密钥已存在,如需修改请手动编辑配置文件")
                return
    
    # 追加写入配置文件
    with open(config_file, 'a') as f:
        f.write(f'\n{env_line}\n')
    
    print(f"密钥已写入{config_file},请重启终端或执行 `source {config_file}` 使配置生效")

if __name__ == '__main__':
    setup_persistent_api_key()

注意:此方法需要用户对自己的Shell配置文件有写入权限,一般默认满足;若用户使用小众Shell,需自行补充配置文件路径。

二、替代方案:使用项目/用户专属配置文件

如果用户不愿修改Shell配置,可采用更轻量化的本地配置文件方案:

方案1:项目根目录.env文件

借助python-dotenv包实现密钥的本地存储与自动读取:

import os
from dotenv import load_dotenv

def setup_project_env():
    env_file = os.path.join(os.path.dirname(__file__), '.env')
    if os.path.exists(env_file):
        print(".env配置文件已存在,如需修改请直接编辑该文件")
        return
    
    api_key = input("请输入你的Gemini API密钥: ").strip()
    if not api_key:
        print("密钥不能为空")
        return
    
    with open(env_file, 'w') as f:
        f.write(f'GEMINI_API_KEY={api_key}\n')
    
    print("密钥已写入项目根目录的.env文件,启动项目时会自动加载")

# 项目启动时加载密钥
load_dotenv()
gemini_api_key = os.getenv('GEMINI_API_KEY')

需先安装依赖:pip install python-dotenv,同时在.gitignore中添加.env,避免密钥提交到版本仓库。

方案2:用户家目录专属配置文件

创建仅当前用户可读的全局配置文件,实现多项目共用密钥:

import os

def setup_home_config():
    config_path = os.path.expanduser('~/.gemini_api_key')
    if os.path.exists(config_path):
        print("全局密钥配置文件已存在,如需修改请编辑该文件")
        return
    
    api_key = input("请输入你的Gemini API密钥: ").strip()
    if not api_key:
        print("密钥不能为空")
        return
    
    with open(config_path, 'w') as f:
        f.write(api_key.strip())
    
    # 设置文件权限为仅当前用户可读
    os.chmod(config_path, 0o600)
    print("密钥已写入~/.gemini_api_key,项目启动时会自动读取")

# 项目中读取密钥的方法
def get_gemini_key():
    config_path = os.path.expanduser('~/.gemini_api_key')
    if not os.path.exists(config_path):
        setup_home_config()
    with open(config_path, 'r') as f:
        return f.read().strip()

此方案无需第三方依赖,且权限设置更安全,避免其他用户读取密钥。

三、关键注意事项

  • 无论采用哪种方案,务必提醒用户不要将密钥文件提交到版本控制系统。
  • 修改Shell配置文件后,需用户重启终端或执行source命令才能生效。
  • 本地配置文件需设置合理权限(如chmod 600),防止密钥泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:03:35