天天看點

生産環境部署python代碼(django+uwsgi+nginx)

基礎環境不做介紹,在django開發web項目完成後,一直使用django自帶的伺服器進行調試:

python manage.py runserver 0.0.0.0:8080

這個伺服器在開發時使用,實際生産則不能滿足,要使用uwsgi把動态請求轉給python執行,使用nginx處理靜态請求,部署如下:

在開發環境中,收集python所需的安裝包及其具體版本号:

pip freeze > programlist.txt

然後,把programlist.txt檔案傳遞伺服器上;

前提:線上伺服器已經安裝好python環境、django環境、nginx等;

在伺服器上安裝python項目所需要的程式包:

pip install -r programlist.txt

建立django項目:

django-admin startprojcet test

會在本地建立一個test項目同名的目錄,并進入:

cd test

再建立項目下的一個應用:

python manage.py starapp apptest

此時,目前目錄會出現apptest目錄、manage.py檔案和test目錄(與項目目錄下同名的又一個目錄);

還要建立相應的目錄:

在項目目錄test下建立目錄:

test/templates/apptest

test/static/apptest

test/static/media

注意:兩級目錄均需要建立

修改settings.py檔案:

DEBUG=False

#允許指定主機通路伺服器

ALLOWED_HOSTS=['*']

#添加應用

INSTALLED_APPS = [

...

'test',

]

#修改模闆路徑

TEMPLATES = [

{

'DIRS': [os.path.join(BASE_DIR,'templates')],

},

#添加靜态檔案路徑

STATIC_URL = '/static/'

STATICFILES_DIRS=[

os.path.join(BASE_DIR,'static')

#nginx配置中的靜态檔案路徑

STATIC_ROOT='/var/www/test/static/'

#配置資料庫

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'test3',

'USER': 'root',

'PASSWORD': 'root',

'HOST': 'localhost',

'PORT': '3306',

}

修改主urls.py檔案:

#配置url路徑

from django.conf.urls import url,include

from django.contrib import admin

urlpatterns = [

url(r'^admin/', admin.site.urls),

url('^',include('booktest.urls')),

在應用目錄下建立一個urls.py檔案:

test/urls.py

如:

from django.conf.urls import url

import views

urlpatterns=[

url(r'^$',views.index),

在views.py檔案裡定義各種視圖函數;

from django.shortcuts import render

def index(request):

return render(request,'booktest/index.html')

在templates/apptest/建立各html模闆檔案;

如index.html:

<head>

<meta charset="UTF-8">

<title>Title</title>

<script src="/static/booktest/jquery-1.12.4.min.js"></script>

</head>

<body>

<img src="/static/booktest/a1.jpg" />

</body>

注意:先把a1.jpg和js檔案放到test/static/apptest目錄下;

此時,先測試一下,把settings中的DEBUG改為=False,如果不改,則會顯示不出圖檔;再啟動django開發時的伺服器,通路浏覽器能看見圖檔且符合js裡面設定的圖檔大小既可進行下一步配置;

下面配置wsgi:

安裝uWSGI:

pip install uwsgi

在項目test目錄下建立uwsgi.ini檔案,内容如下:

[uwsgi]

#使用nginx連接配接,使用socket

socket=192.168.1.250:8080

#直接做web伺服器,使用http

#http=192.168.1.250:8080

#項目的絕對路徑

chdir=/root/projects/test

#相對項目絕對路徑的一個路徑

wsgi-file=test/wsgi.py

processes=4

therads=2

master=True

pidfile=uwsgi.pid

daemonize=uswgi.log

運作uwsgi:

uwsgi --ini uwsgi.ini

如果uwsgi.ini檔案使用的是http,則直接通路伺服器的ip位址和端口既可顯示頁面;

停止uwsgi:

uwsgi --stop uwsgi.pid

如果uwsgi.ini檔案使用的是socket,則需要nginx服務的配合使用:

配置nginx.conf:

server {

listen 80 default_server;

listen [::]:80 default_server;

servername ;

root /usr/share/nginx/html;

include /etc/nginx/default.d/*.conf;

在靜态檔案存放目錄:

/var/www/test/static/

修改靜态檔案所在目錄static的目錄權限:

chmod 777 static

再把靜态檔案,放到/var/www/test/static/目錄下既可,django提供友善的指令,來采集靜态檔案:

python manage.py collectstaic

輸入yes;

執行該指令後,會自動把靜态檔案都複制到/var/www/test/static/目錄下;

最後,直接通路伺服器的域名或ip,完成通路頁面;

本文轉自 crystaleone 51CTO部落格,原文連結:http://blog.51cto.com/linsj/2050731,如需轉載請自行聯系原作者

繼續閱讀