1、編寫django_wsgi.py文件,將其放在與文件manage.py同一個目錄下。
注意: 編寫文件時需要注意語句os.environ.setdefault。比如,如果你的項目爲mydjangosite,則你的語句應該是 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangosite.settings")#!/usr/bin/env python
# coding:utf-8
import os
import sys
DJANGO_PATH = '/disk1/pythonVirtualEnv/python3.4.3/lib/python3.4/site-packages'
print("DJANGO_PATH", DJANGO_PATH)
sys.path.append(DJANGO_PATH)
import django
from django.core.handlers.wsgi import WSGIHandler
from imp import reload
reload(sys)
#sys.setdefaultencoding('utf8') no need for python3.x
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangosite.settings")
django.setup()
application = WSGIHandler()
這一步踩了好多坑,網上好多這個文件都是python2.x版本的,到3.x還需要改,上面的這個文件就是基於3.x的文件
出現的錯誤找不到django模塊,可以通過sys.path.append(DJANGO_PATH)將路徑加入
sys.setdefaultencoding('utf8')這個語句在2.x纔有,3.x是不需要的
django.setup()這個函數3.x才需要,而且必須在在os.environ.setdefault之後調用
2、連接django和uwsgi,實現簡單的WEB服務器
我們假設你的Django項目的地址是/home/ubuntu/mydjangosite然後,就可以執行以下命令:
uwsgi --http-socket :8003 --chdir /home/ubuntu/mydjangosite --module django_wsgi
功能通過瀏覽器就能訪問服務器的8003端口了
3、配置uwsgi:在/home/ubuntu/mydjangosite創建文件 uwsgi.ini
這個配置文件是uwsgi單獨對外提供http服務的配置文件,用這個配置文件的話nginx是無法和它連接成功的,因爲nginx和uwsgi需要用非標準的uwsgi協議
[uwsgi]
http-socket = :8011chdir = /home/ubuntu/mydjangosite
module = django_wsgi
daemonize = django_wsgi.log
<processes>1</processes>
下面這個配置文件是和nginx連接時用的:
[uwsgi]
socket = /home/ubuntu/mydjangosite/uwsgi.sock
#socket = :8011
chdir = /home/ubuntu/mydjangosite
module = django_wsgi
daemonize = django_uwsgi.log
chmod-sokcet = 666
#wsgi-file = django_wsgi.py
#plugin = python
#process = 2
#threads = 2
#stats = 127.0.0.1:8011
4、配置nginx參數
upstream django {server unix:/home/ubuntu/mydjangosite/uwsgi.sock; # for a file socket
# server 127.0.0.1:8011; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 801;
# the domain name it will serve for
server_name www.biseg.cc biseg.cc; # substitute your machine's IP address or FQDN
charset utf-8;
# Django media
location /media {
alias /home/ubuntu/mydjangosite/myjangosite/media;
}
location /static {
alias /home/ubuntu/mydjangosite/myjangosite/static;
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include uwsgi_params;
}
}
5、啓動ngixn, sudo service nginx start
啓動uwsgi, 切換到目錄/home/ubuntu/mydjangosite uwsgi --ini uwsgi.ini啓動nginx, sudo service nginx start
這是通過瀏覽器訪問 網站的801端口就能看到提示 “Congratulations on your first Django-powered page.”
配置基本都是按照下面這兩個教程來的
https://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/uwsgi/