在CentOS上安裝django於apache、WSGI模組與mysql伺服器
操作環境
CentOS 7
Python 3.4
httpd 2.4.6
pip 3.4 8.1.2
django 1.10
PyMySQL 0.7.6
mod_wsgi 3.4
Step1)安裝apache 與mod_wsgi
安裝apache
#yum install httpd
安裝mod_wsgi
#yum install mod_wsgi
Step2)安裝python3.4與pip
#yum install epel-release
#yum install python34
#wget https://bootstrap.pypa.io/get-pip.py
#python3.4 get-pip.py
Step3)安裝django、環境設定與測試
安裝django
#pip3 insall django
修改家目錄下的.bashrc,新增Python3.4的路徑到變數PATH與PYTHONPATH
export PATH=/usr/lib64/python3.4/site-packages/django/bin/:$PATH
export PYTHONPATH=/usr/lib64/python3.4/site-packages/:$PYTHONPATH
測試是否安裝成功,啟用admin畫面
#django-admin.py startproject jweb2
#cd jweb2
#./manage.py makemigrations
#./manage.py migrate
#./manage.py createsuperuser
#./manage.py runserver 8080
使用瀏覽器瀏覽http://127.0.0.1:8080/admin/
Step4)讓jdango在apache上執行
編輯/etc/httpd/conf.d/django.conf
alias /static /home/jian/jweb2/static
<Directory /home/jian/jweb2/static>
Require all granted
</Directory>
WSGIScriptAlias / /home/jian/jweb2/jweb2/wsgi.py
WSGIPythonPath /home/jian/jweb2
<Directory /home/jian/jweb2/jweb2>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess jweb2 python-path=/home/jian/jweb2:/usr/lib64/python3.4/site-packages
WSGIProcessGroup jweb2
Step5)讓外部可以連線apache
新增防火牆規則
#firewall-cmd --permanent --add-service=http
#firewall-cmd --reload
Step6)無法存取網頁時,先關閉selinux
關閉selinux
#setenforce 0
永久關閉selinux,編輯 /etc/sysconfig/selinux,重新開機。
#vi /etc/sysconfig/selinux
SELINUX=disabled
Step7)修改網頁資料夾與檔案的權限
修改家目錄的權限,讓其他人可以瀏覽與讀取
#chmod 755 /home/jian
修改/home/jian/jweb2與/home/jian/jweb2/db.sqlite3的所屬群組,改成apache群組
#chown :apache /home/jian/jweb2
#chown :apache /home/jian/jweb2/db.sqlite3
讓資料庫/home/jian/jweb2/db.sqlite3允許讓apache可以寫入
#chmod 770 /home/jian/jweb2/db.sqlite3
Step8)啟用httpd,使用瀏覽器進行瀏覽
#service httpd restart
預設開機啟用httpd
#systemctl enable httpd
使用瀏覽器連覽,http://your-IP/admin,是否可以看到django的管理網頁,看看Step3的使用者是否能夠登入
Step9)安裝MySQL資料庫
#yum install mariadb
#yum install mariadb-server
#systemctl enable mariadb
#systemctl start mariadb
設定mysql的帳號與密碼,並刪除不必要的權限
#mysql_secure_installation
Step10)讓django可以經由python存取MySQL
安裝套件PyMySQL
#pip3 install pymysql
編輯django專案的__init__.py加上
import pymysql
pymysql.install_as_MySQLdb()
Step11)設定django連線MySQL資料庫
需要在MySQL事先建立資料庫使用者與給予該使用者存取資料庫的權限,接著回到剛剛的myweb專案,更改setting.py連線MySQL資料庫
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '更改為資料庫名稱',
'USER': '更改為資料庫使用者名稱',
'PASSWORD': '更改為資料庫使用者密碼',
'HOST': '',
'PORT': '',
}
}
Step12)使用django在MySQL建立資料表與新增django管理者
#./manage.py makemigrations
#./manage.py migrate
#./manage.py createsuperuser
Step13)使用瀏覽器瀏覽http://your-IP/admin/,看看Step10的使用者是否能夠登入