此次部署重點不在 Django 項目本身,而是為了測試在 Django 框架中集成的微信框架 Werobot
,作為微信個人訂閱號的后臺,測試相關功能。
部署軟硬件準備
- 騰訊云(學生)服務器 (Windows Server 2012 R2)(1G1核1M)
- Apache 2.4.28 Win64(http-2.4.28-win64-VC14.zip)
- mod_wsgi?4.5.19+ap24vc14?cp35?cp35m?win_amd64.whl
- Python-3.5
- Django 1.8
Apache、mod_wsgi、Python
版本分別對上,以 mod_wsgi 版本需要為準
。
安裝 Python
Python 安裝,將 Add Python 3.5 to PATH 選項勾上
,安裝完后可免去命令配置:
安裝完后打開命令行輸入 python,出現如圖指令即安裝成功:
安裝第三方庫
在本地調試的 Django 項目中使用 pip freeze > requirements.txt
命令生成需求庫:
并且配置 settings.py
文件:
# settings.py
DEBUG = False # 關閉調試模式
ALLOWED_HOSTS = ["119.29.92.184",] # 添加服務器公網IP
將整個 Django 項目復制到服務器的目標文件夾中,在項目的根目錄下啟動 cmd.exe,輸入命令 pip install -r requirements.txt
安裝第三方庫:
等待全部安裝成功:
安裝 Mod_wsgi
在 http://www.lfd.uci.edu/~gohlke/pythonlibs/#jsonlib 網站里下載相應版本的 Mod_wsgi 到本地,用 pip install path/to/mod_wsgi
安裝,等待安裝成功后,使用 mod_wsgi-express module-config
查看 mod_wsgi 配置,保存輸出信息。
配置 Apache
將下載好的文件直接解壓到 C 盤根目錄( C 盤為 Apache 默認的安裝路徑),運行 bin 文件下的 httpd.exe
,如果彈出的命令行不閃退,再打開瀏覽器輸入公網 IP ,出現下圖及表示解壓沒問題:
接下來,開始正式配置 Django 項目,打開 conf 文件夾
下的 httpd.conf
配置文件進行配置,首先添加之前配置 mod_wsgi 時輸出的信息
:
# httpd.conf
LoadFile "c:/users/administrator/appdata/local/programs/python/python35/python35.dll"
LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python35/lib/site-packages/mo
d_wsgi/server/mod_wsgi.cp35-win_amd64.pyd"
WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python35"
之后再配置 Django 項目目錄
:
# httpd.conf 基本配置
WSGIScriptAlias / C:/Zhaha/Django/ServerTest1/ServerTest1/wsgi.py
WSGIPythonPath C:/Zhaha/Django/ServerTest1
<Directory C:/Zhaha/Django/ServerTest1/ServerTest1>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
基本配置后,還需要檢查 httpd.conf 配置文件另一些訪問權限
:
# httpd.conf
<Directory /> # 當前版本 229-232 行
AllowOverride none
Require all denied
</Directory>
<Files ".ht*"> # 當前版本 287-289 行
Require all denied
</Files>
改為:
<Directory /> # 當前版本 229-232 行
AllowOverride none
Require all granted
</Directory>
<Files ".ht*"> # 當前版本 287-289 行
Require all denied
</Files>
之后運行 httpd.exe
無閃退即運行成功,下面是 Django 項目一些信息:
# urls.py
...
urlpatterns = [
...
url(r'^wechat/', include("wx_develop.urls"), name="wechat"),
url(r'^robot/', make_view(robot)), # 微信框架
]
# views.py
...
def index_of_wechat(request):
return HttpResponse("You're at the wechat index.")
此時,在外網即可訪問到 Django 項目:
?之后就可以測試 werobot 相關功能,這里不予記錄。
在部署遇到問題的時候可以查看 Apache/logs/error.txt
文件,錯誤日志及提醒都會在里面提示。
此次 Django 部署是基于 Apache 最基本的配置,有些靜態文件路徑并沒有配置到。
Apache 和 mod_wsgi 搭配部署 Django 項目也許并不是最好的組合,但是在學習過程中不需要一步就達到最優解,而是先成型—發現性能不足—再選擇方案優化。
參考資料:
How to use Django with Apache and mod_wsgi
mod_wsgi getting started