简体   繁体   中英

How to update a python dictionary in a dockerfile?

I have a dockerfile which clones a django project at the build time, the settings.py of the django project has a dictionary as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

The above dictionary ie DATABASES needs to be updated as:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ.get('DB_NAME', 'test'),
        'USER': os.environ.get('DB_USER', 'test'),
        'PASSWORD': os.environ.get('DB_PASSWORD', 'test'),
        'HOST': os.environ.get('DB_HOST', 'test'),
        'PORT': os.environ.get('DB_PORT', ''),
    }
}

How could this be done in dockerfile? I have already been using sed commands in dockerfile to replace other single line variable with its values. Please help me updating the dictionary.

Note: I do not have access to commit to the project repository that i'm cloning in dockerfile. So i will need a solution that would perform the above desired change in dockerfile itself.

Manually editing file contents inside the Dockerfile doesn't seem like a good idea.

It'd be much easier to just have two settings files (eg dev_settings.py and prod_settings.py ), and then configure which one the Docker image will use by setting the appropriate environment variable :

ENV DJANGO_SETTINGS_MODULE=myapp.prod_settings

Without modifying the original repo, you can still do the same by creating an override file, for example:

# my_settings.py
from .settings import *
DATABASES = { } # Custom settings here

And then stick it inside the app settings directory during build and set the env var:

# Dockerfile
COPY my_settings.py /myapp/my_settings.py # Next to original settings file
ENV DJANGO_SETTINGS_MODULE=myapp.my_settings

The my_settings.py file only needs to be in your Docker build context, so you don't need to touch the cloned repo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM