간단한 개발 및 배포를 위해 Django를 어떻게 구성합니까?
Django 개발을 할 때 SQLite 를 사용하는 경향이 있지만 라이브 서버에서는 더 강력한 것이 필요합니다 ( 예 : MySQL / PostgreSQL ). Django 설정에는 다른 로깅 위치 / 강도, 미디어 경로 등의 변경 사항이 있습니다.
배포를 간단하고 자동화 된 프로세스로 만들기 위해 이러한 모든 변경 사항을 어떻게 관리합니까?
업데이트 : django-configurations 가 출시되어 수동으로 수행하는 것보다 대부분의 사람들에게 더 나은 옵션 일 것입니다.
수동으로 작업을 수행하려는 경우 이전 답변이 여전히 적용됩니다.
여러 설정 파일이 있습니다.
settings_local.py
-데이터베이스 이름, 파일 경로 등과 같은 호스트 별 구성settings_development.py
-개발에 사용되는 구성, 예DEBUG = True
.settings_production.py
-생산에 사용되는 구성, 예SERVER_EMAIL
.
이 settings.py
파일들을 모두 첫 번째로 settings_local.py
가져온 파일 과 함께 묶은 다음 다른 두 파일 중 하나와 묶습니다 . 그것은 내부의 두 설정에 의해로드 할 결정 settings_local.py
- DEVELOPMENT_HOSTS
와 PRODUCTION_HOSTS
. settings.py
를 platform.node()
실행하여 컴퓨터에서 실행중인 컴퓨터의 호스트 이름을 찾은 다음 목록에서 해당 호스트 이름을 찾은 다음 호스트 이름을 찾는 목록에 따라 두 번째 설정 파일을로드합니다.
그렇게하면 실제로 걱정해야 할 것은 settings_local.py
호스트 별 구성으로 파일을 최신 상태로 유지하는 것 뿐이며 그 밖의 모든 것은 자동으로 처리됩니다.
예를 확인 하십시오 .
개인적으로, 나는 프로젝트에 단일 settings.py를 사용합니다. 프로젝트에있는 호스트 이름을 찾으면됩니다 (개발 시스템에는 "gabriel"로 시작하는 호스트 이름이 있으므로 다음과 같습니다.
import socket
if socket.gethostname().startswith('gabriel'):
LIVEHOST = False
else:
LIVEHOST = True
다른 부분에는 다음과 같은 것들이 있습니다.
if LIVEHOST:
DEBUG = False
PREPEND_WWW = True
MEDIA_URL = 'http://static1.grsites.com/'
else:
DEBUG = True
PREPEND_WWW = False
MEDIA_URL = 'http://localhost:8000/static/'
등등. 조금 덜 읽을 수 있지만 잘 작동하고 여러 설정 파일을 저글링 해야하는 시간을 절약합니다.
settings.py의 끝에 나는 다음을 가지고 있습니다 :
try:
from settings_local import *
except ImportError:
pass
이 방법으로 기본 설정을 재정의하려면 settings.local 바로 옆에 settings_local.py를두면됩니다.
두 개의 파일이 있습니다. settings_base.py
여기에는 공통 / 기본 설정이 포함되며 소스 제어로 체크인됩니다. 각 배포에는 별도의 가 있으며 처음에 settings.py
실행 from settings_base import *
되고 필요에 따라 재정의됩니다.
내가 찾은 가장 간단한 방법은 다음과 같습니다.
1) 로컬 개발에 기본 settings.py 를 사용 하고 2) 다음으로 시작 하여 production-settings.py를 만듭니다 .
import os
from settings import *
그런 다음 프로덕션에서 다른 설정을 무시하십시오.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
....
}
}
Django 자체를 여러 데이터베이스와 함께 배포하는 문제와 관련하여 Djangostack 을 살펴볼 수 있습니다. Apache, Python, Django 등을 설치할 수있는 완전 무료 설치 관리자를 다운로드 할 수 있습니다. 설치 프로세스의 일부로 사용할 데이터베이스 (MySQL, SQLite, PostgreSQL)를 선택할 수 있습니다. 내부적으로 배포를 자동화 할 때 설치 관리자를 광범위하게 사용합니다 (무인 모드에서 실행할 수 있음).
I have my settings.py file in an external directory. That way, it doesn't get checked into source control, or over-written by a deploy. I put this in the settings.py file under my Django project, along with any default settings:
import sys
import os.path
def _load_settings(path):
print "Loading configuration from %s" % (path)
if os.path.exists(path):
settings = {}
# execfile can't modify globals directly, so we will load them manually
execfile(path, globals(), settings)
for setting in settings:
globals()[setting] = settings[setting]
_load_settings("/usr/local/conf/local_settings.py")
Note: This is very dangerous if you can't trust local_settings.py.
In addition to the multiple settings files mentioned by Jim, I also tend to place two settings into my settings.py file at the top BASE_DIR
and BASE_URL
set to the path of the code and the URL to the base of the site, all other settings are modified to append themselves to these.
BASE_DIR = "/home/sean/myapp/"
e.g. MEDIA_ROOT = "%smedia/" % BASEDIR
So when moving the project I only have to edit these settings and not search the whole file.
I would also recommend looking at fabric and Capistrano (Ruby tool, but it can be used to deploy Django applications) which facilitate automation of remote deployment.
Well, I use this configuration:
At the end of settings.py:
#settings.py
try:
from locale_settings import *
except ImportError:
pass
And in locale_settings.py:
#locale_settings.py
class Settings(object):
def __init__(self):
import settings
self.settings = settings
def __getattr__(self, name):
return getattr(self.settings, name)
settings = Settings()
INSTALLED_APPS = settings.INSTALLED_APPS + (
'gunicorn',)
# Delete duplicate settings maybe not needed, but I prefer to do it.
del settings
del Settings
I think it depends on the size of the site as to whether you need to step up from using SQLite, I've successfully used SQLite on several smaller live sites and it runs great.
I use environment:
if os.environ.get('WEB_MODE', None) == 'production' :
from settings_production import *
else :
from settings_dev import *
I believe this is a much better approach, because eventually you need special settings for your test environment, and you can easily add it to this condition.
So many complicated answers!
Every settings.py file comes with :
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
I use that directory to set the DEBUG variable like this (reaplace with the directoy where your dev code is):
DEBUG=False
if(BASE_DIR=="/path/to/my/dev/dir"):
DEBUG = True
Then, every time the settings.py file is moved, DEBUG will be False and it's your production environment.
Every time you need different settings than the ones in your dev environment just use:
if(DEBUG):
#Debug setting
else:
#Release setting
This is an older post but I think if I add this useful library
it will simplify things.
Quickstart
pip install django-configurations
Then subclass the included configurations.Configuration class in your project's settings.py or any other module you're using to store the settings constants, e.g.:
# mysite/settings.py
from configurations import Configuration
class Dev(Configuration):
DEBUG = True
Set the DJANGO_CONFIGURATION
environment variable to the name of the class you just created, e.g. in ~/.bashrc
:
export DJANGO_CONFIGURATION=Dev
and the DJANGO_SETTINGS_MODULE
environment variable to the module import path as usual, e.g. in bash:
export DJANGO_SETTINGS_MODULE=mysite.settings
Alternatively supply the --configuration
option when using Django management commands along the lines of Django's default --settings
command line option, e.g.:
python manage.py runserver --settings=mysite.settings --configuration=Dev
To enable Django to use your configuration you now have to modify your manage.py or wsgi.py script to use django-configurations' versions of the appropriate starter functions, e.g. a typical manage.py using django-configurations would look like this:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
Notice in line 10 we don't use the common tool django.core.management.execute_from_command_line
but instead configurations.management.execute_from_command_line
.
The same applies to your wsgi.py file, e.g.:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')
from configurations.wsgi import get_wsgi_application
application = get_wsgi_application()
Here we don't use the default django.core.wsgi.get_wsgi_application
function but instead configurations.wsgi.get_wsgi_application
.
That's it! You can now use your project with manage.py and your favorite WSGI enabled server.
In fact you should probably consider having the same (or almost the same) configs for your development and production environment. Otherwise, situations like "Hey, it works on my machine" will happen from time to time.
So in order to automate your deployment and eliminate those WOMM issues, just use Docker.
'IT박스' 카테고리의 다른 글
Windows Azure : 웹 역할, 작업자 역할 및 VM 역할이란 무엇입니까? (0) | 2020.07.29 |
---|---|
jQuery로 요소 컨텐츠 변경 감지 (0) | 2020.07.29 |
Eclipse에서 UTF-8 인코딩을 지원하는 방법 (0) | 2020.07.28 |
PHP 함수에 가변 개수의 인수를 전달하는 방법 (0) | 2020.07.28 |
ContentResolver.requestSync가 동기화를 트리거하지 않는 이유는 무엇입니까? (0) | 2020.07.28 |