1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python,django。ローカル環境とサーバー環境ではsettings.pyは分けたほうがよいという話。

Posted at

表題の通り。
ローカル環境とサーバー環境でファイルを分けるのがベストプラクティスだというお話。
djangoですとプロジェクトをスタートさせる際にsettings.pyが自動で作成されます。
例えばlocal_settings.pyなどのファイルを作り、先頭に

from .settings import *

と書くことでsettings.pyの設定が呼び出せます。
その下に書き換えたい部分を記載します。
ローカル環境で使用するlocal_settings.py



DEBUG = True

ALLOWED_HOSTS = []

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

そしてサーバー環境で使用するsettings.pyもサーバー環境用に適応したものに書き換えます。
DEBUG = False #サーバー環境ではFalseとしないとプログラムのエラーメッセージが出てしまう。

ALLOWED_HOSTS = ['使用するホスト名。']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '', #
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}


DATABASESはsqliteからMysqlに書き換えました。 sqliteはローカルなものなのでサーバー環境では外部のデータベースにした方が更新作業などが楽だったためです。 このようにローカル環境とサーバー環境でファイルを分けてしまうといろいろと楽です。

余談ですがlocal_settings.pyで起動させたいときに、以下のような方法があるらしいですが僕はうまくいきませんでした。 https://yoshitaku-jp.hatenablog.com/entry/2018/09/02/004857 http://virgo.hatenadiary.jp/entry/2015/08/30/002245

local_manage.pyというファイルを作りmanage.pyの設定をコピペし、以下部分を
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "プロジェクト名.settings")

こう書き換えます

"プロジェクト名.local_settings"

起動の際に
py local_manage.py runserver

で動作します。


もっとスマートな方法があるように思いますが、ローカル環境とサーバー環境を分けるというのは僕も便利だと思っているので知っておくといいと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?