如何在生產上部署Django?
Django的部署可以有很多方式,采用 nginx+uwsgi 的方式是其中比較常見的一種方式。
uwsgi介紹
uWSGI是一個Web服務器,它實現了WSGI協議、uwsgi、http等協議。Nginx中HttpUwsgiModule的作用是與uWSGI服務器進行交換。
WSGI / uwsgi / uWSGI 這三個概念的區分。
- WSGI是一種Web服務器網關接口。它是一個Web服務器(如nginx,uWSGI等服務器)與web應用(如用Flask框架寫的程序)通信的一種規范。
- uwsgi是一種線路協議而不是通信協議,在此常用于在uWSGI服務器與其他網絡服務器的數據通信。
- 而uWSGI是實現了uwsgi和WSGI兩種協議的Web服務器。
- uwsgi協議是一個uWSGI服務器自有的協議,它用于定義傳輸信息的類型(type of information),每一個uwsgi packet前4byte為傳輸信息類型描述,它與WSGI相比是兩樣東西。
uwsgi性能非常高
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-h5bytglv-1624451195016)(/img/python/1624450446-df75b58c1a0ed8efc087487dd7142768.png)]
uWSGI的主要特點如下
- 超快的性能
- 低內存占用(實測為apache2的mod_wsgi的一半左右)
- 多app管理(終于不用冥思苦想下個app用哪個端口比較好了-.-)
- 詳盡的日志功能(可以用來分析app性能和瓶頸)
- 高度可定制(內存大小限制,服務一定次數后重啟等)
總而言之uwgi是個部署用的好東東,正如uWSGI作者所吹噓的:
If you are searching for a simple wsgi-only server, uWSGI is not for you, but if you are building a real (production-ready) app that need to be rock-solid, fast and easy to distribute/optimize for various load-average, you will pathetically and morbidly fall in love (we hope) with uWSGI.
1、uWSGI安裝使用
pip install uwsgi
# ... or if you want to install the latest LTS (long term support) release,
pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz
基本測試
Create a file called test.py:
# test.py
def application(env, start_response):start_response('200 OK', [('Content-Type','text/html')])return [b"Hello World"] # python3#return ["Hello World"] # python2# 運行
uwsgi --http :8000 --wsgi-file test.py
# 在瀏覽器內輸入:http://127.0.0.1:8001,查看是否有"Hello World"輸出,若沒有輸出,檢查安裝過程。
進入uwsgi安裝目錄,用uwsgi 啟動django
/usr/local/bin/uwsgi --http :8000 --module mysite.wsgi
可以把參數寫到配置文件里
# uwsgi8080.ini####################### 配置一 #####################
[uwsgi]
http = :9000
socket = 127.0.0.1:8001chdir = /home/alex/CrazyEye # the base directory (full path)
wsgi-file = CrazyEye/wsgi.py # your Django's wsgi fileprocesses = 4
threads = 2
stats = 127.0.0.1:9191 # monitor uwsgi status
vacuum = true # clear environment on exit################## 配置二 ###################
# 非多站模式時 vhost = true 和 no-site = true 需要注釋掉,否則后續 nginx 配置文件中設置的入口文件則不生效
[uwsgi]
socket = 127.0.0.1:9090
master = true # 主進程
vhost = true # 多站模式
no-site = true # 多站模式時不設置入口模塊和文件
workers = 2 # 子進程數
reload-mercy = 10
vacuum = true # 退出、重啟時清理文件
max-requests = 1000
limit-as = 512
buffer-size = 30000
pidfile = /var/run/uwsgi9090.pid # pid文件,用于下面的腳本啟動、停止該進程
daemonize = /website/uwsgi9090.log################## 配置三 ###################
[uwsgi]
socket = 127.0.0.1:8080 #socket 為上線使用,http為直接作為服務器使用
http = 127.0.0.1:8000chdir=/home/ray/project # 項目目錄
module=project.wsgi
# 虛擬環境目錄
# home = home/ray/MxOnline/mxonlineEnv
master = true
processes=4
threads=2
# 下面的參數可選
# pidfile=uwsgi.pid uwsgi.pid 和uwsgi.log會在啟動uwsgi時自動生成在項目目錄下。
# daemonize=uswgi.log
# max-requests=2000
# chmod-socket=664
# vacuum=true
參數解析:
- http : 協議類型和端口號
- processes : 開啟的進程數量
- workers : 開啟的進程數量,等同于processes(官網的說法是spawn the specified number ofworkers / processes)
- chdir : 指定運行目錄(chdir to specified directory before apps loading)
- wsgi-file : 載入wsgi-file(load .wsgi file)
- stats : 在指定的地址上,開啟狀態服務(enable the stats server on the specified address)
- threads : 運行線程。由于GIL的存在,我覺得這個真心沒啥用。(run each worker in prethreaded mode with the specified number of threads)
- master : 允許主進程存在(enable master process)
- daemonize : 使進程在后臺運行,并將日志打到指定的日志文件或者udp服務器(daemonize uWSGI)。實際上最常用的,還是把運行記錄輸出到一個本地文件上。
- vacuum : 當服務器退出的時候自動清理環境,刪除unix socket文件和pid文件(try to remove all of the generated file/sockets)
啟動
/usr/local/bin/uwsgi crazye-uwsgi.ini
2、Nginx安裝使用
安裝
sudo apt-get install nginx
sudo /etc/init.d/nginx start
Nginx配置文件
# mysite_nginx.conf# 負載均衡
upstream django {# server unix:///path/to/your/mysite/mysite.sock; # for a file socketserver 127.0.0.1:8001; # for a web port socket (we'll use this first)
}# configuration of the server
server {listen 8000; # 監聽的端口server_name .example.com; # 監聽的域名,或者ipcharset utf-8;# max upload sizeclient_max_body_size 75M; # request請求body# Django medialocation /media {alias /path/to/your/mysite/media; # 項目的media路徑}location /static {alias /path/to/your/mysite/static; # 項目的static 路徑}# Finally, send all non-media requests to the Django server.location / {# uwsgi_pass django; # 上面配置的負載均衡# include /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installedinclude uwsgi_params;uwsgi_pass 127.0.0.1:9090; # 必須和uwsgi中的設置一致# uwsgi_param UWSGI_SCRIPT demosite.wsgi;# 入口文件,即wsgi.py相對于項目根目錄的位置,“.”相當于一層目錄# uwsgi_param UWSGI_CHDIR /demosite; # 項目根目錄index index.html index.htm;}
}
做個超鏈接
sudo ln -s ~/path/to/your/mysite/mysite_nginx.conf /etc/nginx/sites-enabled/
Deploying static files
Before running nginx, you have to collect all Django static files in the static folder. First of all you have to edit mysite/settings.py adding:
STATIC_URL = 'static'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]
在項目目錄下遷移靜態文件
python manage.py collectstatic
此時啟動Nginx 和Uwsgi,你的django項目就可以實現高并發啦!
3、參考
Django中settings.py中的五個設置參數的一些故事:
1、MEDIA_ROOT與MEDIA_URL
事實上MEDIA_ROOT和MEDIA_URL代表的是用戶上傳后的文件一般保存的地方。我的理解是,可變文件的文件夾。
與這兩個參數有聯系的,是在Django的FileField和ImageField這樣的Model類中,有upload_to參數可選。
當upload_to設置相關的地址后,如:upload_to="username";
文件上傳后將自動保存到 os.path.join(MEDIA_ROOT, upload_to)。
而MEDIA_URL,,則代表用戶通過URL來訪問這個本地地址的URL。
如本機http://127.0.0.1/, MEDIA_URL設置為"/site_media/",
那么通過 http://127.0.0.1/site_media/*** 就可以訪問相關的上傳圖片或者其他資源。2、STATIC_ROOT與STATIC_URL
STATIC_ROOT和STATIC_URL則是網站中,用于網站顯示的靜態圖片、CSS、JS等文件的保存地址。
我的理解是,運行中不會再變文件的文件夾(即不會刪除或者新增)2.1 STATIC_URL同MEDIA_URL類似;STATIC_URL為"/static/"時候,通過http://127.0.0.1/static/***就可以訪問相關的靜態文件了。2.2 STATIC_ROOT是一個比較特殊的文件夾。
這是區別Django的開發模式和部署模式下最大的地方了。
通常我們在開發模式下,可以在我們所在的project下建立相應的app, 然后每個app下都建立相應的static文件夾。
在開發模式下(Debug=True),Django將為我們自動查找這些靜態文件(每個app)并在網頁上顯示出來。
然而,在部署模式下,Django認為這些工作交由web服務器來運行會更有效率。
因此,在部署時,我們需要運行一下python manage.py collectstatic 這個命令。
這個命令將會把每個app里的static目錄下的文件copy到STATIC_ROOT這個文件夾下,
這時候如果在部署模式下(Debug=False),網頁中相關的,如: http://127.0.0.1/static/*** 的訪問,
將不會訪問Django下各個App中的static,而是STATIC_ROOT中所指定的文件夾。3、Debug=False后,為何無法訪問圖片和js等文件了?
其實這個問題,是在于web服務器沒有對STATIC_ROOT以及MEDIA_ROOT這兩個文件夾進行映射所導致的。
以apache為例,假定:
STATIC_ROOT="/home/user/static/"
STATIC_URL="/static/"
MEDIA_ROOT="/home/user/media/"
MEDIA_URL="/media/"那么可以在apache的配置文件中,增加以下:
<Location "/static/">
Order deny,allow
Allow from all
Satisfy Any
</Location>
Alias /static/ "/home/user/static"
<Location "/media/">
Order deny,allow
Allow from all
Satisfy Any
</Location>
Alias /media/ "/home/user/media/"4、STATICFILES_DIRS:
和TEMPLATE_DIRS的含義差不多,就是除了各個app的static目錄以外還需要管理的靜態文件,
添加到這里的文件會在collectstatic時 copy到STATIC_ROOT中