共計 2582 個字符,預計需要花費 7 分鐘才能閱讀完成。
這篇文章主要介紹了 Ubuntu 中怎么部署 Django 的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇 Ubuntu 中怎么部署 Django 文章都會有所收獲,下面我們一起來看看吧。
第一步,先更新
sudo apt-get update
sudo apt-get upgrade
Django 的主流部署方式:nginx+uwsgi+django
第二步,安裝 nginx
sudo apt-get install nginx
安裝 nginx,如果需要安裝最新的 nginx 需從官網下載源碼包進行手動編譯。
nginx 的大致文件結構。
1. 配置文件:/etc/nginx
2. 程序:/usr/sbin/nginx
3. 日志:/var/log/nginx/access.log – error.log
第三步,安裝 uwsgi
sudo apt-get install python3-dev
sudo apt-get install python3-pip
sudo pip3 install uwsgi(此步之前,可以換下 pip 源以提高下載速度。在~/.pip 下創建 pip.conf 寫入
[global]
trusted-host = pypi.douban.com
index-url = http://pypi.douban.com/simple)
uwsgi 是一個 web 服務器,它實現了 WSGI 協議、uwsgi、http 等協議。Nginx 中 HttpUwsgiModule 的作用是與 uWSGI 服務器進行交換。
大致流程是:客戶端 == nginx == uwsgi == Django。靜態請求由 Nginx 自己處理。非靜態請求通過 uwsgi 傳遞給 Django,由 Django 來進行處理,從而完成一次 WEB 請求。
創建 Django 測試項目,django-admin startproject mysite,cd mysite,python manage.py startapp demo1。
第四步,測試 uwsgi
在 mysite 目錄下新建測試文件,nano test.py.
寫入:
defapplication(env,start_response):
start_response(200OK ,[( Content-Type , text/html)])
return[HelloWorld]
運行:
uwsgi--http:8001--pluginpython--wsgi-filetest.py
訪問正常。
第五步,測試 Django
pythonmanage.pyrunserver0.0.0.0:8002
訪問正常。
連接 Django 和 uwsgi。
uwsgi--http:8001--pluginpython--modulemysite.wsgi
訪問正常。
第六步,配置 uwsgi
uwsgi 支持通過多種配置文件形式啟動,這里采用 ini 配置文件的方法.
新建 uwsgi:nano uwsgi.ini
#mysite_uwsgi.inifile
[uwsgi]
socket=127.0.0.1:3400
#Django-relatedsettings
#thedjangoprojectdirectory(fullpath)
chdir=/home/ubuntu/mysite
#Django swsgifile
module=mysite.wsgi
#process-relatedsettings
#master
master=true
#maximumnumberofworkerprocesses
processes=2
threads=2
max-requests=6000
#...withappropriatepermissions-maybeneeded
chmod-socket=664
#clearenvironmentonexit
vacuum=true
訪問時報錯,invalid request block size: 21573 (max 4096)…skip。
原因是 url 地址超過 4096 個字符,原因是我們是用 socket 的方式啟動,將配置文件的 socket 改為 http 即可,或者修改 buffer-size。
(建議不做修改,測試時改為 http 即可,等連接 nginx 時,改回到 socket)
daemonize=/home/ubuntu/mysite/uwsgi.log
正式運行時將這句代碼加入到 uwsgi.ini 文件中,訪問日志就會后臺輸出到 uwsgi.log
此時 django 已經能訪問。
第七步,配置 nginx
修改 nginx 的默認配置文件 /etc/nginx/sites-enabled/default
server{
#theportyoursitewillbeservedon
listen80;
#thedomainnameitwillservefor
server_name127.0.0.1;#substituteyourmachine sIPaddressorFQDN
charsetutf-8;
#maxuploadsize
client_max_body_size75M;#adjusttotaste
#Djangomedia
location/media{
alias/home/ubuntu/mysite/media;#yourDjangoproject smediafiles-amendasrequired
location/static{
alias/home/ubuntu/mysite/static;#yourDjangoproject sstaticfiles-amendasrequired
#Finally,sendallnon-mediarequeststotheDjangoserver.
location/{
includeuwsgi_params;#theuwsgi_paramsfileyouinstalled
uwsgi_pass127.0.0.1:8001;# 此處跟 uwsgi 配置文件保持一致
}
記得修改測試時的 uwsgi.ini 的配置。
第八步,運行
關于“Ubuntu 中怎么部署 Django”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Ubuntu 中怎么部署 Django”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注丸趣 TV 行業資訊頻道。