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

如何在Django模板的JS脚本中安全调用.env环境变量?

在Django模板中安全调用.env中的Google Drive凭证

1. 让Django读取.env变量

首先安装python-dotenv工具来加载.env文件:

pip install python-dotenv

在项目根目录的settings.py顶部添加以下代码,确保环境变量能被读取:

from dotenv import load_dotenv
import os

load_dotenv()  # 加载.env中的变量

# 可添加以下代码验证变量是否加载成功(可选)
GOOGLE_DRIVE_API_KEY = os.getenv('GOOGLE_DRIVE_API_KEY')
GOOGLE_DRIVE_API_CLIENT_ID = os.getenv('GOOGLE_DRIVE_API_CLIENT_ID')
GOOGLE_DRIVE_APP_ID = os.getenv('GOOGLE_DRIVE_APP_ID')

2. 将变量传递到模板

有两种常用方式:

方式一:单个视图传递(仅给指定模板用)

在对应视图函数中,把凭证变量加入渲染上下文:

from django.shortcuts import render
import os

def your_target_view(request):
    context = {
        'drive_api_key': os.getenv('GOOGLE_DRIVE_API_KEY'),
        'drive_client_id': os.getenv('GOOGLE_DRIVE_API_CLIENT_ID'),
        'drive_app_id': os.getenv('GOOGLE_DRIVE_APP_ID'),
    }
    return render(request, 'your_template.html', context)

方式二:全局上下文处理器(所有模板通用)

  1. 在你的app目录下创建context_processors.py文件,写入:
import os

def google_drive_credentials(request):
    return {
        'drive_api_key': os.getenv('GOOGLE_DRIVE_API_KEY'),
        'drive_client_id': os.getenv('GOOGLE_DRIVE_API_CLIENT_ID'),
        'drive_app_id': os.getenv('GOOGLE_DRIVE_APP_ID'),
    }
  1. 在settings.py的TEMPLATES配置中,将这个处理器加入上下文列表:
TEMPLATES = [
    {
        # ... 其他已有配置
        'OPTIONS': {
            'context_processors': [
                # ... 默认的处理器(比如django.contrib.auth.context_processors.auth等)
                'your_app_name.context_processors.google_drive_credentials',
            ],
        },
    },
]

3. 在模板JS中安全使用变量

方法一:直接插入模板变量(简单场景)

用|safe过滤器避免Django转义特殊字符:

<script>
    var API_KEY = '{{ drive_api_key|safe }}';
    var CLIENT_ID = '{{ drive_client_id|safe }}';
    var APP_ID = '{{ drive_app_id|safe }}';
    var SCOPES = 'https://www.googleapis.com/auth/drive';
</script>

方法二:使用json_script标签(更安全,防XSS)

先在模板HTML部分添加:

{{ drive_api_key|json_script:"drive-api-key" }}
{{ drive_client_id|json_script:"drive-client-id" }}
{{ drive_app_id|json_script:"drive-app-id" }}

再在JS中读取:

<script>
    var API_KEY = JSON.parse(document.getElementById('drive-api-key').textContent);
    var CLIENT_ID = JSON.parse(document.getElementById('drive-client-id').textContent);
    var APP_ID = JSON.parse(document.getElementById('drive-app-id').textContent);
    var SCOPES = 'https://www.googleapis.com/auth/drive';
</script>

关键安全提示

  • 浏览器端使用的Google Drive API Key必然会暴露在前端代码中,所以必须在Google Cloud控制台限制该Key的使用范围:
    • 仅允许指定域名的HTTP请求调用
    • 仅授权Google Drive相关API
  • 绝对不要将服务账号密钥等敏感凭证传到前端,这类凭证只能在后端服务器使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:17:50