Home > Backend Development > Python Tutorial > Update Django Key using .env

Update Django Key using .env

Susan Sarandon
Release: 2024-11-29 05:41:10
Original
141 people have browsed it

Update Django Key using .env

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")
Copy after login

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")
Copy after login

Then run it as:

 python manage.py mk_key
Copy after login

The above is the detailed content of Update Django Key using .env. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template