CentOS服務器配置Nginx搀罢、uwsgi實現(xiàn)Android文件上傳功能

系統(tǒng)準備

首先艘绍,我們安裝yum-utils,一個yum的拓展庫泉沾,能夠實現(xiàn)完整得yum功能和插件
sudo yum -y install yum-utils
接下來安卓CentOS開發(fā)者工具捞蚂,用于編譯源代碼
sudo yum -y groupinstall development

安裝python3

安裝IUS
sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm
安裝最新版本python
sudo yum -y install python36u
檢查python版本
python3.6 -V
接下來安裝python36u0devel包,提供了python3環(huán)境下需要的庫和頭文件
sudo yum -y install python36u-devel

配置虛擬環(huán)境

虛擬環(huán)境可以提供獨立的環(huán)境給不同的python項目跷究,保證你的項目有獨立的依賴不會干擾到其他項目 姓迅。每個編程環(huán)境都可以安裝不同的python庫
選擇一個路徑去放置python編程環(huán)境
cd opt/
mkdir python-virtual-dev
cd python-virtual-dev
python-3.6 demo
接著進入該環(huán)境
source demo/bin/activate
安裝django庫
pip install django
安裝uwsgi
pip install uwsgi

配置Nginx

安裝
yum -y install eqel-release
yum repolist
yum install nignx
安裝完打開nginx服務
systemctl start nginx
并且測試初始頁是否能完成服務
X.X.X.X(瀏覽本機IP地址)
接著修改nginx主配置文件
systemctl stop nginx
'cd /etc/nginx'
vim nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

#    server {
#        listen       80 default_server;
#        listen       [::]:80 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }
}  

配置文件
cd conf.d
vim vitrual.conf

# configuration of the server
server {
    # the port your site will be served on
    listen 8080;
    # the domain name it will serve for
    server_name  X.X.X.X; # substitute your machine's IP address or FQDN
    error_log /srv/www/yt_demo/logs/error.log;
    access_log /srv/www/yt_demo/logs/access.log;
    charset     utf-8;

    # Django media
    location /media/  {
        alias /srv/www/yt_demo/media/;  # your Django project's media files - amend as required
    }

    location /static/ {
        alias /srv/www/yt_demo/static/; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  unix:/opt/uwsgi/sock/yt_demo.sock;
        include    uwsgi_params; # the uwsgi_params file you installed
    }

創(chuàng)建用戶組

useradd -s /bin/false -r uwsgi

創(chuàng)建Django項目

進入虛擬環(huán)境
source /opt/python-virtual-env/demo/bin/activate
選擇路徑創(chuàng)建項目
cd srv/
mkdir www
cd www
django admin startproject yt_demo
創(chuàng)建logs目錄記錄log文件
mkdir logs
cd logs
創(chuàng)建空文件
vim error.log
vim access.log
接下來修改文件權限保證nginx能夠擁有訪問權限
chown nginx:nginx -R yt_demo/
返回yt_demo文件夾并創(chuàng)建static和media文件夾
mkdir static
mkdir media

配置uwsgi

cd /etc
mkdir uwsgi
cd uwsgi
vim emperor.ini

[uwsgi]
emperor = /etc/uwsgi/vassals
uid = uwsgi
gid = nginx
logto = /etc/uwsgi/log

創(chuàng)建log文件
vim log
vassals配置
mkdir vassals
vim demo.ini

[uwsgi]
http = :8000
socket = /opt/uwsgi/sock/yt_demo.sock
chdir = /srv/www/yt_demo
pythonpath = /srv/www/yt_demo/yt_demo
home = /opt/python-virtual-env/demo
module = yt_demo.wsgi
uid = uwsgi
chmod-socket = 664
chown-socket = uwsgi

修改系統(tǒng)uwsgi配置
cd /etc/systemd/system
vim uwsgi.service

[Unit]
Description=uWSGI Emperor
After=syslog.target

[Service]
ExecStart = /opt/python-virtual-env/demo/bin/uwsgi --ini /etc/uwsgi/emperor.ini
ExecStop = kill -INT `cat /run/uwsgi.pid`
ExecReload = kill -TERM `cat /run/uwsgi.pid`
Restart = always
Type = notify
NotifyAccess = main
PIDFile = /run/uwsgi.pid

[Install]
WantedBy=multi-user.target

創(chuàng)建sock

cd /opt/
mkdir sock
修改訪問權限
'chown uwsgi:uwsgi /opt/uwsgi'
接下來測試配置是否成功
systemctl start nginx
systemctl start uwsgi

Django接受文件

創(chuàng)建Django應用

進入yt_demo項目路徑
cd /srv/www/yt_demo/
創(chuàng)建應用
python manage.py startapp swim
修改/swim/views.py

from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import traceback

from . import models

@csrf_exempt
def Uploadfile(request):
    if request.method == 'GET':
        return HttpResponse("Get success")
    elif request.method == 'POST':
        try:
           # newtxt = models.Txt(txtfile = request.FILE['accData'])
           # newtxt.save()
            swim_txt = request.FILES.get('accData')
            #with open('/srv/www/yt_demo/media/acc/acc.txt','wb+') as destination:
             #   for chunk in swim_txt.chunks():
              #      destination.write(chunk)
            path = default_storage.save('/srv/www/yt_demo/media/acc/'+swim_txt.name,ContentFile(swim_txt.read()))
            return HttpResponse('POST success')
        except:
            tb = traceback.format_exc()
            return HttpResponse(tb)
    else:
        return HttpResponse('Other request')
    #if request.method == 'POST':
       # try:
           # swim_txt = request.FILES.get('accData')
           # path = default_storage.save('User/static/User/swimdata/'+swim_txt.name,ContentFile(swim_txt.read()))
       # return HttpResponse('File got')
      # except:
            #return HttpResponse('File failed')

def index(request):
    return HttpResponse("Hello,world.You're at the swim index.")
# Create your views here.

修改swim/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$',views.index,name = 'index'),
    url(r'^Uploadfile/$',views.Uploadfile,name = 'Uploadfile'),
]

修改yt_demo/urls.py

from django.conf.urls import url,include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^swim/', include('swim.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

記得修改media文件夾的訪問權限防止出現(xiàn)權限問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市俊马,隨后出現(xiàn)的幾起案子丁存,更是在濱河造成了極大的恐慌,老刑警劉巖柴我,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件解寝,死亡現(xiàn)場離奇詭異,居然都是意外死亡艘儒,警方通過查閱死者的電腦和手機聋伦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來界睁,“玉大人觉增,你說我怎么就攤上這事》澹” “怎么了逾礁?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長访惜。 經常有香客問我嘹履,道長,這世上最難降的妖魔是什么债热? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任砾嫉,我火速辦了婚禮,結果婚禮上窒篱,老公的妹妹穿的比我還像新娘焰枢。我一直安慰自己蚓峦,他們只是感情好,可當我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布济锄。 她就那樣靜靜地躺著暑椰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪荐绝。 梳的紋絲不亂的頭發(fā)上一汽,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天,我揣著相機與錄音低滩,去河邊找鬼召夹。 笑死,一個胖子當著我的面吹牛恕沫,可吹牛的內容都是我干的监憎。 我是一名探鬼主播,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼婶溯,長吁一口氣:“原來是場噩夢啊……” “哼鲸阔!你這毒婦竟也來了?” 一聲冷哼從身側響起迄委,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤褐筛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叙身,有當地人在樹林里發(fā)現(xiàn)了一具尸體渔扎,經...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年信轿,在試婚紗的時候發(fā)現(xiàn)自己被綠了晃痴。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡财忽,死狀恐怖倘核,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情定罢,我是刑警寧澤,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布旁瘫,位于F島的核電站祖凫,受9級特大地震影響,放射性物質發(fā)生泄漏酬凳。R本人自食惡果不足惜惠况,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望宁仔。 院中可真熱鬧稠屠,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至攘蔽,卻和暖如春龙屉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背满俗。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工转捕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人唆垃。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓五芝,卻偏偏與公主長得像,于是被迫代替她去往敵國和親辕万。 傳聞我的和親對象是個殘疾皇子枢步,可洞房花燭夜當晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內容