7.9 KiB
Django-Environ Configuration Fix
Summary
Fixed the configuration in config/settings/base.py to properly use django-environ for all environment variables, ensuring consistent and secure environment variable management.
Issue Identified
The config/settings/base.py file was using django-environ for most configuration, but the Social Media API Configuration section at the bottom was using an undefined config() function instead of the proper env() object. This would cause a NameError when Django tried to read social media API credentials.
Changes Made
1. Fixed Social Media API Configuration (config/settings/base.py)
Before:
YOUTUBE_API_KEY = config('YOUTUBE_API_KEY', default=None)
GOOGLE_LOCATIONS = config('GOOGLE_LOCATIONS', default=None, cast=lambda v: v.split(',') if v else None)
ANALYSIS_BATCH_SIZE = config('ANALYSIS_BATCH_SIZE', default=10, cast=int)
ANALYSIS_ENABLED = config('ANALYSIS_ENABLED', default=True, cast=bool)
After:
YOUTUBE_API_KEY = env('YOUTUBE_API_KEY', default=None)
GOOGLE_LOCATIONS = env.list('GOOGLE_LOCATIONS', default=[])
ANALYSIS_BATCH_SIZE = env.int('ANALYSIS_BATCH_SIZE', default=10)
ANALYSIS_ENABLED = env.bool('ANALYSIS_ENABLED', default=True)
2. Updated .env.example File
Added comprehensive social media API configuration section with all required environment variables:
# Social Media API Configuration
# YouTube
YOUTUBE_API_KEY=your-youtube-api-key
YOUTUBE_CHANNEL_ID=your-channel-id
# Facebook
FACEBOOK_PAGE_ID=your-facebook-page-id
FACEBOOK_ACCESS_TOKEN=your-facebook-access-token
# Instagram
INSTAGRAM_ACCOUNT_ID=your-instagram-account-id
INSTAGRAM_ACCESS_TOKEN=your-instagram-access-token
# Twitter/X
TWITTER_BEARER_TOKEN=your-twitter-bearer-token
TWITTER_USERNAME=your-twitter-username
# LinkedIn
LINKEDIN_ACCESS_TOKEN=your-linkedin-access-token
LINKEDIN_ORGANIZATION_ID=your-linkedin-organization-id
# Google Reviews
GOOGLE_CREDENTIALS_FILE=client_secret.json
GOOGLE_TOKEN_FILE=token.json
GOOGLE_LOCATIONS=location1,location2,location3
# OpenRouter AI Configuration
OPENROUTER_API_KEY=your-openrouter-api-key
OPENROUTER_MODEL=anthropic/claude-3-haiku
ANALYSIS_BATCH_SIZE=10
ANALYSIS_ENABLED=True
Django-Environ Benefits
Type Conversion
django-environ provides built-in type conversion methods:
env('KEY')- String (default)env.int('KEY')- Integerenv.bool('KEY')- Booleanenv.list('KEY')- List (comma-separated)env.float('KEY')- Floatenv.dict('KEY')- Dictionaryenv.db('KEY')- Database URL parsingenv.email('KEY')- Email validationenv.path('KEY')- Path object
Error Handling
- Automatic validation of environment variables
- Clear error messages for missing or invalid values
- Type-safe configuration loading
- Default value support for optional variables
Security
- Environment variables loaded from
.envfile (not in version control) - Sensitive credentials never committed to code
- Different values for development, staging, and production
.env.exampleshows required variables without exposing values
Usage Examples
Basic Usage
# Read from environment
DEBUG = env('DEBUG', default=False)
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOSTS = env('ALLOWED_HOSTS', default=[])
Type-Specific Methods
# Integer
PORT = env.int('PORT', default=8000)
# Boolean
DEBUG = env.bool('DEBUG', default=False)
# List (comma-separated)
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=['localhost'])
# Database URL
DATABASES = {
'default': env.db('DATABASE_URL', default='sqlite:///db.sqlite3')
}
Multiple Environments
# Development
DEBUG = env.bool('DEBUG', default=True)
# Production (in production .env)
# DEBUG=False
# SECRET_KEY=production-secret-key
Project Configuration Status
✓ Dependencies
django-environ>=0.11.0is already inpyproject.tomldependencies
✓ Configuration Files
config/settings/base.py- Updated to useenv()consistently.env.example- Updated with all social media API variables
✓ Environment Variables
All environment variables now use django-environ methods:
env()- String valuesenv.bool()- Boolean valuesenv.int()- Integer valuesenv.list()- List valuesenv.db()- Database URLs (commented out)
Environment Variable Reference
Core Django Settings
SECRET_KEY- Django secret keyDEBUG- Debug mode (bool)ALLOWED_HOSTS- Allowed hosts (list)
Database
DATABASE_URL- PostgreSQL connection string
Celery
CELERY_BROKER_URL- Redis connection stringCELERY_RESULT_BACKEND- Redis connection string
EMAIL_BACKEND- Email backendEMAIL_HOST- SMTP serverEMAIL_PORT- SMTP port (int)EMAIL_USE_TLS- Use TLS (bool)EMAIL_HOST_USER- SMTP usernameEMAIL_HOST_PASSWORD- SMTP passwordDEFAULT_FROM_EMAIL- Default sender email
Social Media APIs
YOUTUBE_API_KEY- YouTube Data API keyYOUTUBE_CHANNEL_ID- YouTube channel IDFACEBOOK_PAGE_ID- Facebook page IDFACEBOOK_ACCESS_TOKEN- Facebook access tokenINSTAGRAM_ACCOUNT_ID- Instagram account IDINSTAGRAM_ACCESS_TOKEN- Instagram access tokenTWITTER_BEARER_TOKEN- Twitter/X bearer tokenTWITTER_USERNAME- Twitter usernameLINKEDIN_ACCESS_TOKEN- LinkedIn access tokenLINKEDIN_ORGANIZATION_ID- LinkedIn organization IDGOOGLE_CREDENTIALS_FILE- Google credentials file pathGOOGLE_TOKEN_FILE- Google token file pathGOOGLE_LOCATIONS- Google locations listOPENROUTER_API_KEY- OpenRouter API keyOPENROUTER_MODEL- AI model nameANALYSIS_BATCH_SIZE- Batch size for analysis (int)ANALYSIS_ENABLED- Enable analysis (bool)
Notifications
SMS_ENABLED- Enable SMS (bool)SMS_PROVIDER- SMS providerWHATSAPP_ENABLED- Enable WhatsApp (bool)WHATSAPP_PROVIDER- WhatsApp providerEMAIL_ENABLED- Enable email (bool)EMAIL_PROVIDER- Email provider
Best Practices
- Never commit
.envfile - Add to.gitignore - Keep
.env.exampleupdated - Document all required variables - Use type-specific methods -
env.bool(),env.int(),env.list() - Provide sensible defaults - Use
default=parameter - Validate in production - Ensure all required variables are set
- Document variable formats - Include examples in
.env.example - Rotate secrets regularly - Update keys and tokens periodically
Testing
To verify the configuration works correctly:
# Copy example to .env
cp .env.example .env
# Edit .env with your values
nano .env
# Run Django check
python manage.py check
# Run development server
python manage.py runserver
Troubleshooting
NameError: name 'config' is not defined
Problem: Using config() instead of env()
Solution: Ensure all environment variables use env() method
ValueError for type conversion
Problem: Invalid value format for type
Solution: Check .env file values match expected types
Missing environment variable
Problem: Required variable not set
Solution: Add variable to .env file or provide default value
Migration Notes
If migrating from existing configuration:
- Review all
config()calls inbase.py - Replace with appropriate
env()methods - Update
.env.examplewith all variables - Test in development environment first
- Deploy to production after validation
Related Documentation
Summary
The django-environ configuration has been fixed and is now consistent throughout the project. All environment variables use the proper env() methods with type conversion, and the .env.example file provides a complete reference for all required configuration variables.