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

使用os.environ.get获取AWS密钥时Django网站运行问题求助

Got it, let's fix this properly—exposing AWS keys in your repo is a huge no-no, so you're right to prioritize cleaning this up. Here's a step-by-step solution that works for both local development and Heroku deployment, without risking your sensitive credentials:

1. Local Development: Use a .env File (No Hardcoded Defaults)

Hardcoding placeholder keys like "aaaa" is risky because even if you think they're dummy values, it's easy to accidentally replace them with real ones later, or forget to remove them before pushing. Instead, use a local environment file that's never committed to Git:

  • First, install the python-dotenv package to load local environment variables:
    pip install python-dotenv
    
  • Create a .env file in your Django project's root directory (same folder as manage.py), and add your actual local AWS credentials here:
    AWS_ACCESS_KEY_ID=your_real_local_aws_key
    AWS_SECRET_ACCESS_KEY=your_real_local_aws_secret
    
  • Add .env to your .gitignore file immediately—this ensures it never gets pushed to GitLab:
    # .gitignore
    .env
    
  • Update your settings.py to load the .env file and fetch the credentials without hardcoded defaults:
    from dotenv import load_dotenv
    import os
    from pathlib import Path
    
    # Define your project base directory (if not already present)
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # Load variables from .env for local development
    load_dotenv(os.path.join(BASE_DIR, '.env'))
    
    # Fetch AWS credentials from environment variables
    AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
    AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
    
    # Optional: Add a safety check to catch missing credentials locally
    if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
        raise ValueError("AWS credentials not found! Check your .env file.")
    
2. Heroku Deployment: Use Config Vars

Heroku provides a secure way to store environment variables without committing them to code. Here's how to set them up:

  • Using the Heroku CLI (make sure you're logged in first with heroku login):
    # Navigate to your project directory
    cd your-django-project
    
    # Set the AWS credentials as Heroku config vars
    heroku config:set AWS_ACCESS_KEY_ID=your_production_aws_key
    heroku config:set AWS_SECRET_ACCESS_KEY=your_production_aws_secret
    
  • Alternatively, you can set these via the Heroku Dashboard: Go to your app → Settings → Config Vars, then add the two key-value pairs manually.

Django will automatically pick up these variables from Heroku's environment, so your existing os.environ.get lines in settings.py will work perfectly here—no extra changes needed.

3. Why Your Previous "Other Config" Might Have Failed

If your site broke when you changed the config, here are the most common culprits:

  • You forgot to install python-dotenv, so your local environment wasn't loading the .env file, leaving AWS_ACCESS_KEY_ID as None.
  • Your .env file was in the wrong directory (it needs to be at the project root, or you need to specify its path in load_dotenv).
  • You misspelled the environment variable names in either your .env file or Heroku's config vars (they're case-sensitive—AWS_ACCESS_KEY_ID is not the same as aws_access_key_id).
  • You didn't set the config vars in Heroku at all, so the production app couldn't fetch the credentials.
4. Extra Security Best Practices
  • Never use AWS root credentials: Create a dedicated IAM user for your Django app with only the permissions it needs (e.g., S3 read/write if you're using S3 for media storage). This limits damage if the keys ever leak.
  • Rotate your keys regularly: AWS lets you generate new access keys for IAM users—do this every few months, especially if you're still testing and sharing code.
  • Keep your GitLab repo private eventually: Even with all these safeguards, public repos for production code are risky. Once you're done practicing, switch it to private.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:23:35