programing

Django 로컬 설정

nasanasas 2020. 11. 6. 08:22
반응형

Django 로컬 설정


Django 1.2 에서 local_setting을 사용하려고하는데 작동하지 않습니다. 현재 저는 프로젝트에 local_settings.py추가하고 있습니다.

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'banco1',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '123',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

local_settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'banco2',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '123',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

문제는 local_settings.pysettings.py를 재정의하지 않는다는 것 입니다. 뭐가 잘못 되었 니?


local_settings.py를 추가 할 수는 없으며 명시 적으로 가져와야합니다.

settings.py 맨 끝에 다음 을 추가하십시오.

try:
    from local_settings import *
except ImportError:
    pass

try / except 블록이 있으므로 Python은 실제로 local_settings 파일을 정의하지 않은 경우를 무시합니다.


이것이 내가 생각하는 모범 사례입니다.

  • local_settings 수입 settings
  • local_settings지역 환경에 대한 재정의 설정을 특정, 특히 DATABASES, SECRET_KEY, ALLOWED_HOSTSDEBUG변수
  • django 관리 명령에 플래그 전달 --settings=local_settings

다음 local_settings과 같이 구현할 수 있습니다 .

from settings import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'banco2',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '123',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

몇 가지 추가 핵심 사항 :

  • settings.py 기고자가 사용할 준비가 된 방식으로 작성된 버전 제어
  • local_settings.py(또는 더 일반적으로 prod_settings.py) 버전 제어가 아니며 프로덕션에서 지정 --settings=prod_settings하거나 유사하게 사용됩니다.

재고 설정 파일을 가능한 한 적게 터치하면 장고 버전을 쉽게 업그레이드 할 수 있습니다. Django를 다음 버전으로 업그레이드 할 때 재고 settings.py와 귀하 의 재고 차이를 확인하고 변경된 사항에 따라 필요한 조치를 취하십시오. 기본값의 변경은 중요 할 수 있으며 원본 settings.py파일을 덜 건드릴수록 업스트림 변경 사항을 더 쉽게 식별 할 수 있습니다.


주제가 일상적으로 다시 등장하므로이 접근 방식을 고려할 수있는 이유를 요약하겠습니다.

  • 멍청한 설정 파일은 매우 빠르고 쉽게 변경할 수 있습니다. 특히 생산 환경에서. 파이썬이 필요하지 않습니다. 어떤 바보라도 이름과 값을 나열하는 파일에서 데이터베이스 암호를 변경할 수 있습니다. 특히 신비한 위험한 BIGCAPS 이름으로 가득 찬 복잡한 파이썬 설정 파일과 비교됩니다.

  • 응용 프로그램 settings응용 프로그램과 완전히 분리되어야합니다 code. 저장소 루트 외부에 config.ini를 넣을 수 있으며 설정을 방해하는 저장소 풀이나 저장소를 오염시키는 개인 설정 또는 settings.py의 영리한 코드가 다른 모든 사람에게 유리하게 저장소에 들어 가지 않을까 걱정할 필요가 없습니다. .

이것은 소규모 프로젝트에는 적용되지 않지만, 더 큰 프로젝트에서는 local_settings 전략이 그것을 자르지 않는다는 결론을 내 렸습니다. 시간이 지남에 따라 충분한 애플리케이션 프로그래밍이 처리하기 어려워집니다. 주로 설정이 미분 및 / 또는 상호 의존적이 될 때. local_settings파일 가져 오기가 중간으로 올라가도록 강제하는 로컬 설정에 따라 반응하는 설정에 대한 적절한 이유가있을 수 있습니다 settings.py. 그렇게되면 일이 지저분 해지기 시작합니다.

내 현재 해결책은 config파일 을 사용하는 것입니다. "local.ini"라고합니다. 배치 된 인스턴스간에 실제로 변경되는 값만 보유합니다. 코드는 없습니다. 단지 값과 부울 일뿐입니다.

[global]
domain = 127.0.0.1:8000
database_host = 127.0.0.1
database_name = test_database
debug = Yes
google_analytics_id = UA-DEV-1
payments = testing
use_cdn = No

이를 통해 settings.py다른 애플리케이션 코드와 마찬가지로 처리 할 수 있습니다. local_settings 파이썬 코드에 숨어있을 수있는 코드에 대해 테스트 할 필요없이이를 조정하고, 체크인하고, 배포 할 수 있습니다. My settings.py는 나중에 설정이 로컬 설정에 의존 할 때 발생하는 경쟁 조건이 없으며 따르기 쉬운 선형 코드 작성 기능을 켜고 끌 수 있습니다. 더 이상 서둘러 내가 새로운 가치를 추가하는 잊어 버린 경우 local_settings에 파일을 조정하지 않고, 더 이상 daves_local_settings.pybobs_local_settings.py파일 저장소에 들어온다 없습니다.

from ConfigParser import RawConfigParser
parser = RawConfigParser()

APPLICATION_ROOT = path.abspath(path.dirname(__file__))
parser.readfp(open(path.join(APPLICATION_ROOT, 'local.ini')))

# simple variables
DATABASE_HOST = parser.get('global', 'database_host')
DATABASE_NAME = parser.get('global', 'database_name')

# interdependencies
from version import get_cdn_version
CDN = 'd99phdomw5k72k.cloudfront.net'
if parser.getboolean('global', 'use_cdn'):
    STATIC_URL = '/{}/static/{}/'.format(CDN, get_cdn_version())
else:
    STATIC_URL = '/static/'


# switches
payments = parser.get('global', 'payments')
if payments == 'testing':
    PAYMENT_GATEWAY_ENDPOINT = 'https://api.sandbox.gateway.com'
else:
    PAYMENT_GATEWAY_ENDPOINT = 'https://api.live.gateway.com'

당신이 발생하는 경우 BOFH을 내가 한 경우에 한 것처럼, 그는 특히 스틱 수있는 능력에 대해 흥분 local.ini/etc같은 디렉토리 /etc/ourapp.ini등 응용 프로그램 디렉토리 자체 순수한 저장소 수출을 유지. 물론 local_settings.py로 할 수는 있지만 그가 원했던 마지막 일은 파이썬 코드를 엉망으로 만드는 것이 었습니다. 그가 처리 할 수있는 간단한 구성 파일.


다음의 사본을 보관했습니다 __local_settings.py.

  • local_settings.py 버전 제어에서 무시되지만 __local_settings.py
  • README.md설정 방법에 대해 팀에 알리도록 업데이트 : cp {__,}local_settings.py(local_settings에 대한 사본을 만듭니다)

과거에

이러한 설정을 가져 오곤했습니다.

# settings.py
DATABASE = {...}

try:
    from .local_settings import *
except ImportError:
    pass

지금

에서 설정 자체를 가져옵니다 local_settings.py.

그리고 다음 명령을 사용 python manage.py runserver --settings=<proj>.local_settings합니다..

# local_settings.py & __local_settings.py
from .settings import *

DATABASE = {...}

And since, I usually don't interact with manage.py directly, because some parameters are explicitly necessary for me, (e.g. address:port). Therefore, I put all of those command into my Makefile.

For example, here's my Makefile:

run:
    python manage.py runserver 0.0.0.0:8000 --settings=<proj>.local_settings

sh:
    python manage.py shell_plus --settings=<proj>.local_settings

dep:
    npm install
    pip install -r requirements.txt

Thus:

make dep
make sh 
make run

Conclusion

Provided that you are not using Makefile as your workflow, then you may use the earlier method, but if you are using makefile, then i believe it is better to be more explicit in your Makefile.


Before running the server do

export DJANGO_SETTINGS_MODULE=your_app_name.local_settings where your_app_name should be replaced by your App's name. And don't forget to do

from settings import *

in your local_settings.py file


Yet another approach is to use python-dotenv and environment variables to customize settings for different environments.

Create the .env file along-side your settings.py:

# .env
SECRET_KEY=your-secret-key
DATABASE_PASSWORD=your-database-password

Add the following code to your settings.py:

# settings.py
from dotenv import load_dotenv
load_dotenv()

# OR, explicitly providing path to '.env'
from pathlib import Path  # python 3.4+
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

At this point, parsed keys/values from the .env file are present as environment variables and they can be conveniently accessed via os.getenv():

# settings.py
import os
SECRET_KEY = os.getenv('SECRET_KEY')
DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD')   

I found the similar solution. This is my configuration for this case:

settings.py:

DEBUG = False

try:
    from local_settings import *

except ImportError:
    pass

if DEBUG is False:
    ALLOWED_HOSTS = ['sth.com']
    DATABASES = {
        ....
    }

local_settings.py:

from settings import *
ALLOWED_HOSTS = ['*']
DEBUG = True
DATABASES = {
    ...
}

Add this to the end of the file settings.py

try:
    from .local_settings import *
except ImportError:
    pass

And create file local_settings.py with your new settings for example

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'banco2',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '123',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

참고URL : https://stackoverflow.com/questions/4909958/django-local-settings

반응형