#前言 為了在AWS上面作個後台,根據同事的介紹,找到了Django,不過佈建上花了不少功夫,終於在uWSGI官網,找到了一個相當完整的介紹,下面就把他筆記下來。
#架構
瀏覽器 <-> the web server(nginx) <-> uWSGI <-> Django
上述架構很明顯總共有幾段要處理的
-
瀏覽器 與 nginx
-
nginx 與 uWSGI
-
uWSGI 與 Django
#前置安裝 安裝Python
sudo apt-get install python
sudo apt-get install python-dev #需要先安裝這個不然不能執行pip
安裝uWSGI
sudo pip install uwsgi
安裝nginx
sudo apt-get install nginx
安裝Django
sudo pip install Django
#開始
##測試 uWSGI 與 Python 可用
先寫一個test.py在 /home/ubuntu/ 底下
# test.py
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return ["Hello World"] # python2
#return [b"Hello World"] # python3接著 Run uWSGI
uwsgi --http :8000 --wsgi-file test.py
接著你應該可以用瀏覽器輸入網址
http://xx.xx.xx.xxx:8000 //請輸入你的Server IP
這時你應該看到 Hello World了
##實作 Django 這時候你應該還是在 /home/ubuntu 底下,輸入
django-admin.py startproject mysite
你會產生下面這樣的資料夾結構與檔案
- mysite
- mysite
- __init__.py
- settings.py
- urls.py
- wsgi.py
- manage.py
接著切換到mysite底下
cd mysite
你現在是在 /home/ubuntu/mysite,之後在輸入
python manage.py runserver 0.0.0.0:8000
如果沒有顯示任何錯誤的話,在輸入
uwsgi --http :8000 --module mysite.wsgi
然後瀏覽器端重新整理剛剛網址後,你應該會看到 "It worked!",這表示你完成了
瀏覽器 <-> uWSGI <-> Django
##開始設定 Nginx 將資料夾切到 nginx 的設定資料夾底下
cd /etc/nginx/
開啟nginx的設定檔
sudo vim nginx.conf
作下面一些修正
user ubuntu; //把第一行的user www-data改掉
在http{ 最下面加入
# the upstream component nginx needs to connect to
upstream django {
#server unix:/home/ubuntu/mysite.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 8000;
# the domain name it will serve for
server_name .example.com; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias /home/ubuntu/mysite/media; # your Django project's media files - amend as required
}
location /static {
alias /home/ubuntu/mysite/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
}
接著設定Django /home/ubuntu/mysite/mysite
vim /home/ubuntu/mysite/mysite/setting.py
增加一行文件最下面
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
換回到 /home/ubuntu/mysite
cd /home/ubuntu/mysite
輸入下面指令讓Django Project初始化
python manage.py collectstatic
新增一個media資料夾在mysite底下
mkdir media
新增一個測試檔案test.txt在media資料夾底下
cd media //切到media
vim test.txt //新增一個test.txt 並輸入個 Hello Django World
確認一下所有資料夾應該是如下
- mysite
- media
- test.txt
- static
- mysite
- __init__.py
- settings.py
- urls.py
- wsgi.py
- manage.py
重啟nginx
sudo /etc/init.d/nginx restart
在瀏覽器上輸入
http://xx.xx.xx.xxx/media/test.txt
你應該會看到 Hello Django World ,表示你也完成了
瀏覽器 <-> nginx