使用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:
.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-dotenvpackage to load local environment variables:pip install python-dotenv - Create a
.envfile in your Django project's root directory (same folder asmanage.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
.envto your.gitignorefile immediately—this ensures it never gets pushed to GitLab:# .gitignore .env - Update your
settings.pyto load the.envfile 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.")
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.
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.envfile, leavingAWS_ACCESS_KEY_IDasNone. - Your
.envfile was in the wrong directory (it needs to be at the project root, or you need to specify its path inload_dotenv). - You misspelled the environment variable names in either your
.envfile or Heroku's config vars (they're case-sensitive—AWS_ACCESS_KEY_IDis not the same asaws_access_key_id). - You didn't set the config vars in Heroku at all, so the production app couldn't fetch the credentials.
- 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

