Laravel that I usually code has a command that updates the encryption key at .env
file. To be honest, I love this approach and I wanted to replicate upon my django project.
Therefore, I followed these steps:
Step 1: Load .env
file
See: https://dev.to/pcmagas/how-to-load-env-in-django-project-4c9d
Step 2: Use SECRET_KEY
env file:
At settings.py
Do:
SECRET_KEY = os.getenv('SECRET_KEY',None)
if SECRET_KEY is None:
raise RuntimeError("SECRET_KEY value is not defined upon .env file")
Step 3 Create a command that update the .env
:
I made the script myapp/management/commands/mk_key.py
with the following (replace myapp
with your own application name):
from django.core.management.base import BaseCommand
from django.core.management.utils import get_random_secret_key
import os
class Command(BaseCommand):
help = 'Create a new Secret Key'
def handle(self, *args, **kwargs):
key = get_random_secret_key()
env_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',"..","..",'.env')
self.updateDotenv(env_file_path,key)
def updateDotenv(self,env_file_path,key):
with open(env_file_path, 'r') as file:
lines = file.readlines()
# Update the SECRET_KEY line
updated_lines = []
for line in lines:
if line.startswith('SECRET_KEY'):
continue
else:
updated_lines.append(line)
line = f"SECRET_KEY='{key}'\n"
updated_lines.insert(0,line) # Replace with new key
# Write the updated lines back to the .env file
with open(env_file_path, 'w') as file:
file.writelines(updated_lines)
# Output the new secret key
self.stdout.write(f"Updated .env\n")
Then run it as:
python manage.py mk_key
Top comments (0)