阿里雲部署Django專案(超詳細圖文教程)—— Part3. Django settings修改、PostgreSQL配置

馬志峰的程式設計筆記發表於2015-11-14

阿里雲部署Django專案(超詳細圖文教程)

Part3. Django settings修改、PostgreSQL配置

前言:

花了一個月的空閒時間,終於成功把Django網站部署到了阿里雲ECS上,包含以下功能:

  • 不使用任何第三方工具,直接用網頁連線阿里雲ECS
  • 使用GIT進行原始碼控制和上傳到伺服器
  • 使用git hooks實現自動部署
  • 用的是時下比較流行的一套部署方案——Nginx, Gunicorn, virtualenv, supervisor and PostgreSQL
  • 可以在同一臺伺服器上部署兩個、甚至多個網站

光說不練假把式,建議大家邊看邊操作!

Django 釋出設定

  • 釋出環境下修改Debug為False

    這裡根據主機名來判斷是否在釋出環境

    import socket
    
    if socket.gethostname() == 'iZ94m6lerh2Z':
        DEBUG = TEMPLATE_DEBUG = False
    else:
        DEBUG = TEMPLATE_DEBUG = True
    

    伺服器主機名有兩種方式獲得:

    1. 在管理控制檯檢視
    2. 在管理終端用命令檢視
  • 在伺服器上建立資料庫並進行配置

    sudo su - postgres
    createuser --interactive -P

按照提示輸入名稱和密碼

Enter name of role to add: hello_django
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

為了提高資料庫安全,可以去https://www.grc.com/passwords.htm生成一個複雜度更高的密碼

建立資料庫

createdb --owner hello_django hello
logout
  • 修改settings檔案資料庫配置

    if DEBUG:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': 'hello',
                'USER': 'hello_django',
                'PASSWORD': '1Ak5RTQt7mtw0OREsfPhJYzXIak41gnrm5NWYEosCeIduJck10awIzoys1wvbL8',
                'HOST': 'localhost',
                'PORT': '',                      
            }
        }
    else:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            }
        }
    
  • 修改Admiin、Host

    ADMINS = (
        ('woniu02141', '380238062@qq.com'),
    )
    ALLOWED_HOSTS = ['localhost', '.woniu02141.com']
    
    MANAGERS = ADMINS
    
  • 修改時區

    TIME_ZONE = 'Asia/Shanghai'
    
    LANGUAGE_CODE = 'zh-cn'
    
  • 修改StaticRoot等

    STATIC_ROOT = '/webapps/woniu/static/'
    STATIC_URL = 'http://woniu02141.com/static/'
    
    MEDIA_ROOT = '/webapps/woniu/media/'
    MEDIA_URL = 'http://woniu02141.com/media/'
    
  • 在伺服器端,同步資料庫,收集靜態檔案

    /webapps/woniu/bin/python3.4 manage.py syncdb
    /webapps/woniu/bin/python3.4 manage.py collectstatic
    

在這裡根據virtualenv建立的python環境來選擇python路徑

備註: 連線資料庫時出現一些認證情況的解決辦法:

  • 如果出現下面的錯誤:

    FATAL: Ident authentication failed for user “mypguser”

請編輯你的pg_hba.conf,這個檔案一般位於/etc/postgresql/X.Y/main/pg_hba.conf,X.Y是你的PostgreSQL的版本號,將下面行的peer改為trust:

local all all trust 
  • 如果出現下面的錯誤:

    FATAL: Peer authentication failed for user “mypguser”

請仍然修改pg_hba.conf檔案,該下面行的peer為md5:
local all all md5

完成上面的修改後請重新載入postgresql:
/etc/init.d/postgresql reload

相關文章